xref: /openbmc/linux/drivers/infiniband/sw/rdmavt/qp.c (revision f8e9a970)
1 /*
2  * Copyright(c) 2016 - 2020 Intel Corporation.
3  *
4  * This file is provided under a dual BSD/GPLv2 license.  When using or
5  * redistributing this file, you may do so under either license.
6  *
7  * GPL LICENSE SUMMARY
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of version 2 of the GNU General Public License as
11  * published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * General Public License for more details.
17  *
18  * BSD LICENSE
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  *
24  *  - Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  *  - Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in
28  *    the documentation and/or other materials provided with the
29  *    distribution.
30  *  - Neither the name of Intel Corporation nor the names of its
31  *    contributors may be used to endorse or promote products derived
32  *    from this software without specific prior written permission.
33  *
34  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
35  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
36  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
37  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
38  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
39  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
40  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
41  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
42  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
43  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
44  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45  *
46  */
47 
48 #include <linux/hash.h>
49 #include <linux/bitops.h>
50 #include <linux/lockdep.h>
51 #include <linux/vmalloc.h>
52 #include <linux/slab.h>
53 #include <rdma/ib_verbs.h>
54 #include <rdma/ib_hdrs.h>
55 #include <rdma/opa_addr.h>
56 #include <rdma/uverbs_ioctl.h>
57 #include "qp.h"
58 #include "vt.h"
59 #include "trace.h"
60 
61 #define RVT_RWQ_COUNT_THRESHOLD 16
62 
63 static void rvt_rc_timeout(struct timer_list *t);
64 static void rvt_reset_qp(struct rvt_dev_info *rdi, struct rvt_qp *qp,
65 			 enum ib_qp_type type);
66 
67 /*
68  * Convert the AETH RNR timeout code into the number of microseconds.
69  */
70 static const u32 ib_rvt_rnr_table[32] = {
71 	655360, /* 00: 655.36 */
72 	10,     /* 01:    .01 */
73 	20,     /* 02     .02 */
74 	30,     /* 03:    .03 */
75 	40,     /* 04:    .04 */
76 	60,     /* 05:    .06 */
77 	80,     /* 06:    .08 */
78 	120,    /* 07:    .12 */
79 	160,    /* 08:    .16 */
80 	240,    /* 09:    .24 */
81 	320,    /* 0A:    .32 */
82 	480,    /* 0B:    .48 */
83 	640,    /* 0C:    .64 */
84 	960,    /* 0D:    .96 */
85 	1280,   /* 0E:   1.28 */
86 	1920,   /* 0F:   1.92 */
87 	2560,   /* 10:   2.56 */
88 	3840,   /* 11:   3.84 */
89 	5120,   /* 12:   5.12 */
90 	7680,   /* 13:   7.68 */
91 	10240,  /* 14:  10.24 */
92 	15360,  /* 15:  15.36 */
93 	20480,  /* 16:  20.48 */
94 	30720,  /* 17:  30.72 */
95 	40960,  /* 18:  40.96 */
96 	61440,  /* 19:  61.44 */
97 	81920,  /* 1A:  81.92 */
98 	122880, /* 1B: 122.88 */
99 	163840, /* 1C: 163.84 */
100 	245760, /* 1D: 245.76 */
101 	327680, /* 1E: 327.68 */
102 	491520  /* 1F: 491.52 */
103 };
104 
105 /*
106  * Note that it is OK to post send work requests in the SQE and ERR
107  * states; rvt_do_send() will process them and generate error
108  * completions as per IB 1.2 C10-96.
109  */
110 const int ib_rvt_state_ops[IB_QPS_ERR + 1] = {
111 	[IB_QPS_RESET] = 0,
112 	[IB_QPS_INIT] = RVT_POST_RECV_OK,
113 	[IB_QPS_RTR] = RVT_POST_RECV_OK | RVT_PROCESS_RECV_OK,
114 	[IB_QPS_RTS] = RVT_POST_RECV_OK | RVT_PROCESS_RECV_OK |
115 	    RVT_POST_SEND_OK | RVT_PROCESS_SEND_OK |
116 	    RVT_PROCESS_NEXT_SEND_OK,
117 	[IB_QPS_SQD] = RVT_POST_RECV_OK | RVT_PROCESS_RECV_OK |
118 	    RVT_POST_SEND_OK | RVT_PROCESS_SEND_OK,
119 	[IB_QPS_SQE] = RVT_POST_RECV_OK | RVT_PROCESS_RECV_OK |
120 	    RVT_POST_SEND_OK | RVT_FLUSH_SEND,
121 	[IB_QPS_ERR] = RVT_POST_RECV_OK | RVT_FLUSH_RECV |
122 	    RVT_POST_SEND_OK | RVT_FLUSH_SEND,
123 };
124 EXPORT_SYMBOL(ib_rvt_state_ops);
125 
126 /* platform specific: return the last level cache (llc) size, in KiB */
127 static int rvt_wss_llc_size(void)
128 {
129 	/* assume that the boot CPU value is universal for all CPUs */
130 	return boot_cpu_data.x86_cache_size;
131 }
132 
133 /* platform specific: cacheless copy */
134 static void cacheless_memcpy(void *dst, void *src, size_t n)
135 {
136 	/*
137 	 * Use the only available X64 cacheless copy.  Add a __user cast
138 	 * to quiet sparse.  The src agument is already in the kernel so
139 	 * there are no security issues.  The extra fault recovery machinery
140 	 * is not invoked.
141 	 */
142 	__copy_user_nocache(dst, (void __user *)src, n, 0);
143 }
144 
145 void rvt_wss_exit(struct rvt_dev_info *rdi)
146 {
147 	struct rvt_wss *wss = rdi->wss;
148 
149 	if (!wss)
150 		return;
151 
152 	/* coded to handle partially initialized and repeat callers */
153 	kfree(wss->entries);
154 	wss->entries = NULL;
155 	kfree(rdi->wss);
156 	rdi->wss = NULL;
157 }
158 
159 /*
160  * rvt_wss_init - Init wss data structures
161  *
162  * Return: 0 on success
163  */
164 int rvt_wss_init(struct rvt_dev_info *rdi)
165 {
166 	unsigned int sge_copy_mode = rdi->dparms.sge_copy_mode;
167 	unsigned int wss_threshold = rdi->dparms.wss_threshold;
168 	unsigned int wss_clean_period = rdi->dparms.wss_clean_period;
169 	long llc_size;
170 	long llc_bits;
171 	long table_size;
172 	long table_bits;
173 	struct rvt_wss *wss;
174 	int node = rdi->dparms.node;
175 
176 	if (sge_copy_mode != RVT_SGE_COPY_ADAPTIVE) {
177 		rdi->wss = NULL;
178 		return 0;
179 	}
180 
181 	rdi->wss = kzalloc_node(sizeof(*rdi->wss), GFP_KERNEL, node);
182 	if (!rdi->wss)
183 		return -ENOMEM;
184 	wss = rdi->wss;
185 
186 	/* check for a valid percent range - default to 80 if none or invalid */
187 	if (wss_threshold < 1 || wss_threshold > 100)
188 		wss_threshold = 80;
189 
190 	/* reject a wildly large period */
191 	if (wss_clean_period > 1000000)
192 		wss_clean_period = 256;
193 
194 	/* reject a zero period */
195 	if (wss_clean_period == 0)
196 		wss_clean_period = 1;
197 
198 	/*
199 	 * Calculate the table size - the next power of 2 larger than the
200 	 * LLC size.  LLC size is in KiB.
201 	 */
202 	llc_size = rvt_wss_llc_size() * 1024;
203 	table_size = roundup_pow_of_two(llc_size);
204 
205 	/* one bit per page in rounded up table */
206 	llc_bits = llc_size / PAGE_SIZE;
207 	table_bits = table_size / PAGE_SIZE;
208 	wss->pages_mask = table_bits - 1;
209 	wss->num_entries = table_bits / BITS_PER_LONG;
210 
211 	wss->threshold = (llc_bits * wss_threshold) / 100;
212 	if (wss->threshold == 0)
213 		wss->threshold = 1;
214 
215 	wss->clean_period = wss_clean_period;
216 	atomic_set(&wss->clean_counter, wss_clean_period);
217 
218 	wss->entries = kcalloc_node(wss->num_entries, sizeof(*wss->entries),
219 				    GFP_KERNEL, node);
220 	if (!wss->entries) {
221 		rvt_wss_exit(rdi);
222 		return -ENOMEM;
223 	}
224 
225 	return 0;
226 }
227 
228 /*
229  * Advance the clean counter.  When the clean period has expired,
230  * clean an entry.
231  *
232  * This is implemented in atomics to avoid locking.  Because multiple
233  * variables are involved, it can be racy which can lead to slightly
234  * inaccurate information.  Since this is only a heuristic, this is
235  * OK.  Any innaccuracies will clean themselves out as the counter
236  * advances.  That said, it is unlikely the entry clean operation will
237  * race - the next possible racer will not start until the next clean
238  * period.
239  *
240  * The clean counter is implemented as a decrement to zero.  When zero
241  * is reached an entry is cleaned.
242  */
243 static void wss_advance_clean_counter(struct rvt_wss *wss)
244 {
245 	int entry;
246 	int weight;
247 	unsigned long bits;
248 
249 	/* become the cleaner if we decrement the counter to zero */
250 	if (atomic_dec_and_test(&wss->clean_counter)) {
251 		/*
252 		 * Set, not add, the clean period.  This avoids an issue
253 		 * where the counter could decrement below the clean period.
254 		 * Doing a set can result in lost decrements, slowing the
255 		 * clean advance.  Since this a heuristic, this possible
256 		 * slowdown is OK.
257 		 *
258 		 * An alternative is to loop, advancing the counter by a
259 		 * clean period until the result is > 0. However, this could
260 		 * lead to several threads keeping another in the clean loop.
261 		 * This could be mitigated by limiting the number of times
262 		 * we stay in the loop.
263 		 */
264 		atomic_set(&wss->clean_counter, wss->clean_period);
265 
266 		/*
267 		 * Uniquely grab the entry to clean and move to next.
268 		 * The current entry is always the lower bits of
269 		 * wss.clean_entry.  The table size, wss.num_entries,
270 		 * is always a power-of-2.
271 		 */
272 		entry = (atomic_inc_return(&wss->clean_entry) - 1)
273 			& (wss->num_entries - 1);
274 
275 		/* clear the entry and count the bits */
276 		bits = xchg(&wss->entries[entry], 0);
277 		weight = hweight64((u64)bits);
278 		/* only adjust the contended total count if needed */
279 		if (weight)
280 			atomic_sub(weight, &wss->total_count);
281 	}
282 }
283 
284 /*
285  * Insert the given address into the working set array.
286  */
287 static void wss_insert(struct rvt_wss *wss, void *address)
288 {
289 	u32 page = ((unsigned long)address >> PAGE_SHIFT) & wss->pages_mask;
290 	u32 entry = page / BITS_PER_LONG; /* assumes this ends up a shift */
291 	u32 nr = page & (BITS_PER_LONG - 1);
292 
293 	if (!test_and_set_bit(nr, &wss->entries[entry]))
294 		atomic_inc(&wss->total_count);
295 
296 	wss_advance_clean_counter(wss);
297 }
298 
299 /*
300  * Is the working set larger than the threshold?
301  */
302 static inline bool wss_exceeds_threshold(struct rvt_wss *wss)
303 {
304 	return atomic_read(&wss->total_count) >= wss->threshold;
305 }
306 
307 static void get_map_page(struct rvt_qpn_table *qpt,
308 			 struct rvt_qpn_map *map)
309 {
310 	unsigned long page = get_zeroed_page(GFP_KERNEL);
311 
312 	/*
313 	 * Free the page if someone raced with us installing it.
314 	 */
315 
316 	spin_lock(&qpt->lock);
317 	if (map->page)
318 		free_page(page);
319 	else
320 		map->page = (void *)page;
321 	spin_unlock(&qpt->lock);
322 }
323 
324 /**
325  * init_qpn_table - initialize the QP number table for a device
326  * @rdi: rvt dev struct
327  * @qpt: the QPN table
328  */
329 static int init_qpn_table(struct rvt_dev_info *rdi, struct rvt_qpn_table *qpt)
330 {
331 	u32 offset, i;
332 	struct rvt_qpn_map *map;
333 	int ret = 0;
334 
335 	if (!(rdi->dparms.qpn_res_end >= rdi->dparms.qpn_res_start))
336 		return -EINVAL;
337 
338 	spin_lock_init(&qpt->lock);
339 
340 	qpt->last = rdi->dparms.qpn_start;
341 	qpt->incr = rdi->dparms.qpn_inc << rdi->dparms.qos_shift;
342 
343 	/*
344 	 * Drivers may want some QPs beyond what we need for verbs let them use
345 	 * our qpn table. No need for two. Lets go ahead and mark the bitmaps
346 	 * for those. The reserved range must be *after* the range which verbs
347 	 * will pick from.
348 	 */
349 
350 	/* Figure out number of bit maps needed before reserved range */
351 	qpt->nmaps = rdi->dparms.qpn_res_start / RVT_BITS_PER_PAGE;
352 
353 	/* This should always be zero */
354 	offset = rdi->dparms.qpn_res_start & RVT_BITS_PER_PAGE_MASK;
355 
356 	/* Starting with the first reserved bit map */
357 	map = &qpt->map[qpt->nmaps];
358 
359 	rvt_pr_info(rdi, "Reserving QPNs from 0x%x to 0x%x for non-verbs use\n",
360 		    rdi->dparms.qpn_res_start, rdi->dparms.qpn_res_end);
361 	for (i = rdi->dparms.qpn_res_start; i <= rdi->dparms.qpn_res_end; i++) {
362 		if (!map->page) {
363 			get_map_page(qpt, map);
364 			if (!map->page) {
365 				ret = -ENOMEM;
366 				break;
367 			}
368 		}
369 		set_bit(offset, map->page);
370 		offset++;
371 		if (offset == RVT_BITS_PER_PAGE) {
372 			/* next page */
373 			qpt->nmaps++;
374 			map++;
375 			offset = 0;
376 		}
377 	}
378 	return ret;
379 }
380 
381 /**
382  * free_qpn_table - free the QP number table for a device
383  * @qpt: the QPN table
384  */
385 static void free_qpn_table(struct rvt_qpn_table *qpt)
386 {
387 	int i;
388 
389 	for (i = 0; i < ARRAY_SIZE(qpt->map); i++)
390 		free_page((unsigned long)qpt->map[i].page);
391 }
392 
393 /**
394  * rvt_driver_qp_init - Init driver qp resources
395  * @rdi: rvt dev strucutre
396  *
397  * Return: 0 on success
398  */
399 int rvt_driver_qp_init(struct rvt_dev_info *rdi)
400 {
401 	int i;
402 	int ret = -ENOMEM;
403 
404 	if (!rdi->dparms.qp_table_size)
405 		return -EINVAL;
406 
407 	/*
408 	 * If driver is not doing any QP allocation then make sure it is
409 	 * providing the necessary QP functions.
410 	 */
411 	if (!rdi->driver_f.free_all_qps ||
412 	    !rdi->driver_f.qp_priv_alloc ||
413 	    !rdi->driver_f.qp_priv_free ||
414 	    !rdi->driver_f.notify_qp_reset ||
415 	    !rdi->driver_f.notify_restart_rc)
416 		return -EINVAL;
417 
418 	/* allocate parent object */
419 	rdi->qp_dev = kzalloc_node(sizeof(*rdi->qp_dev), GFP_KERNEL,
420 				   rdi->dparms.node);
421 	if (!rdi->qp_dev)
422 		return -ENOMEM;
423 
424 	/* allocate hash table */
425 	rdi->qp_dev->qp_table_size = rdi->dparms.qp_table_size;
426 	rdi->qp_dev->qp_table_bits = ilog2(rdi->dparms.qp_table_size);
427 	rdi->qp_dev->qp_table =
428 		kmalloc_array_node(rdi->qp_dev->qp_table_size,
429 			     sizeof(*rdi->qp_dev->qp_table),
430 			     GFP_KERNEL, rdi->dparms.node);
431 	if (!rdi->qp_dev->qp_table)
432 		goto no_qp_table;
433 
434 	for (i = 0; i < rdi->qp_dev->qp_table_size; i++)
435 		RCU_INIT_POINTER(rdi->qp_dev->qp_table[i], NULL);
436 
437 	spin_lock_init(&rdi->qp_dev->qpt_lock);
438 
439 	/* initialize qpn map */
440 	if (init_qpn_table(rdi, &rdi->qp_dev->qpn_table))
441 		goto fail_table;
442 
443 	spin_lock_init(&rdi->n_qps_lock);
444 
445 	return 0;
446 
447 fail_table:
448 	kfree(rdi->qp_dev->qp_table);
449 	free_qpn_table(&rdi->qp_dev->qpn_table);
450 
451 no_qp_table:
452 	kfree(rdi->qp_dev);
453 
454 	return ret;
455 }
456 
457 /**
458  * rvt_free_qp_cb - callback function to reset a qp
459  * @qp: the qp to reset
460  * @v: a 64-bit value
461  *
462  * This function resets the qp and removes it from the
463  * qp hash table.
464  */
465 static void rvt_free_qp_cb(struct rvt_qp *qp, u64 v)
466 {
467 	unsigned int *qp_inuse = (unsigned int *)v;
468 	struct rvt_dev_info *rdi = ib_to_rvt(qp->ibqp.device);
469 
470 	/* Reset the qp and remove it from the qp hash list */
471 	rvt_reset_qp(rdi, qp, qp->ibqp.qp_type);
472 
473 	/* Increment the qp_inuse count */
474 	(*qp_inuse)++;
475 }
476 
477 /**
478  * rvt_free_all_qps - check for QPs still in use
479  * @rdi: rvt device info structure
480  *
481  * There should not be any QPs still in use.
482  * Free memory for table.
483  * Return the number of QPs still in use.
484  */
485 static unsigned rvt_free_all_qps(struct rvt_dev_info *rdi)
486 {
487 	unsigned int qp_inuse = 0;
488 
489 	qp_inuse += rvt_mcast_tree_empty(rdi);
490 
491 	rvt_qp_iter(rdi, (u64)&qp_inuse, rvt_free_qp_cb);
492 
493 	return qp_inuse;
494 }
495 
496 /**
497  * rvt_qp_exit - clean up qps on device exit
498  * @rdi: rvt dev structure
499  *
500  * Check for qp leaks and free resources.
501  */
502 void rvt_qp_exit(struct rvt_dev_info *rdi)
503 {
504 	u32 qps_inuse = rvt_free_all_qps(rdi);
505 
506 	if (qps_inuse)
507 		rvt_pr_err(rdi, "QP memory leak! %u still in use\n",
508 			   qps_inuse);
509 	if (!rdi->qp_dev)
510 		return;
511 
512 	kfree(rdi->qp_dev->qp_table);
513 	free_qpn_table(&rdi->qp_dev->qpn_table);
514 	kfree(rdi->qp_dev);
515 }
516 
517 static inline unsigned mk_qpn(struct rvt_qpn_table *qpt,
518 			      struct rvt_qpn_map *map, unsigned off)
519 {
520 	return (map - qpt->map) * RVT_BITS_PER_PAGE + off;
521 }
522 
523 /**
524  * alloc_qpn - Allocate the next available qpn or zero/one for QP type
525  *	       IB_QPT_SMI/IB_QPT_GSI
526  * @rdi: rvt device info structure
527  * @qpt: queue pair number table pointer
528  * @type: the QP type
529  * @port_num: IB port number, 1 based, comes from core
530  * @exclude_prefix: prefix of special queue pair number being allocated
531  *
532  * Return: The queue pair number
533  */
534 static int alloc_qpn(struct rvt_dev_info *rdi, struct rvt_qpn_table *qpt,
535 		     enum ib_qp_type type, u8 port_num, u8 exclude_prefix)
536 {
537 	u32 i, offset, max_scan, qpn;
538 	struct rvt_qpn_map *map;
539 	u32 ret;
540 	u32 max_qpn = exclude_prefix == RVT_AIP_QP_PREFIX ?
541 		RVT_AIP_QPN_MAX : RVT_QPN_MAX;
542 
543 	if (rdi->driver_f.alloc_qpn)
544 		return rdi->driver_f.alloc_qpn(rdi, qpt, type, port_num);
545 
546 	if (type == IB_QPT_SMI || type == IB_QPT_GSI) {
547 		unsigned n;
548 
549 		ret = type == IB_QPT_GSI;
550 		n = 1 << (ret + 2 * (port_num - 1));
551 		spin_lock(&qpt->lock);
552 		if (qpt->flags & n)
553 			ret = -EINVAL;
554 		else
555 			qpt->flags |= n;
556 		spin_unlock(&qpt->lock);
557 		goto bail;
558 	}
559 
560 	qpn = qpt->last + qpt->incr;
561 	if (qpn >= max_qpn)
562 		qpn = qpt->incr | ((qpt->last & 1) ^ 1);
563 	/* offset carries bit 0 */
564 	offset = qpn & RVT_BITS_PER_PAGE_MASK;
565 	map = &qpt->map[qpn / RVT_BITS_PER_PAGE];
566 	max_scan = qpt->nmaps - !offset;
567 	for (i = 0;;) {
568 		if (unlikely(!map->page)) {
569 			get_map_page(qpt, map);
570 			if (unlikely(!map->page))
571 				break;
572 		}
573 		do {
574 			if (!test_and_set_bit(offset, map->page)) {
575 				qpt->last = qpn;
576 				ret = qpn;
577 				goto bail;
578 			}
579 			offset += qpt->incr;
580 			/*
581 			 * This qpn might be bogus if offset >= BITS_PER_PAGE.
582 			 * That is OK.   It gets re-assigned below
583 			 */
584 			qpn = mk_qpn(qpt, map, offset);
585 		} while (offset < RVT_BITS_PER_PAGE && qpn < RVT_QPN_MAX);
586 		/*
587 		 * In order to keep the number of pages allocated to a
588 		 * minimum, we scan the all existing pages before increasing
589 		 * the size of the bitmap table.
590 		 */
591 		if (++i > max_scan) {
592 			if (qpt->nmaps == RVT_QPNMAP_ENTRIES)
593 				break;
594 			map = &qpt->map[qpt->nmaps++];
595 			/* start at incr with current bit 0 */
596 			offset = qpt->incr | (offset & 1);
597 		} else if (map < &qpt->map[qpt->nmaps]) {
598 			++map;
599 			/* start at incr with current bit 0 */
600 			offset = qpt->incr | (offset & 1);
601 		} else {
602 			map = &qpt->map[0];
603 			/* wrap to first map page, invert bit 0 */
604 			offset = qpt->incr | ((offset & 1) ^ 1);
605 		}
606 		/* there can be no set bits in low-order QoS bits */
607 		WARN_ON(rdi->dparms.qos_shift > 1 &&
608 			offset & ((BIT(rdi->dparms.qos_shift - 1) - 1) << 1));
609 		qpn = mk_qpn(qpt, map, offset);
610 	}
611 
612 	ret = -ENOMEM;
613 
614 bail:
615 	return ret;
616 }
617 
618 /**
619  * rvt_clear_mr_refs - Drop help mr refs
620  * @qp: rvt qp data structure
621  * @clr_sends: If shoudl clear send side or not
622  */
623 static void rvt_clear_mr_refs(struct rvt_qp *qp, int clr_sends)
624 {
625 	unsigned n;
626 	struct rvt_dev_info *rdi = ib_to_rvt(qp->ibqp.device);
627 
628 	if (test_and_clear_bit(RVT_R_REWIND_SGE, &qp->r_aflags))
629 		rvt_put_ss(&qp->s_rdma_read_sge);
630 
631 	rvt_put_ss(&qp->r_sge);
632 
633 	if (clr_sends) {
634 		while (qp->s_last != qp->s_head) {
635 			struct rvt_swqe *wqe = rvt_get_swqe_ptr(qp, qp->s_last);
636 
637 			rvt_put_qp_swqe(qp, wqe);
638 			if (++qp->s_last >= qp->s_size)
639 				qp->s_last = 0;
640 			smp_wmb(); /* see qp_set_savail */
641 		}
642 		if (qp->s_rdma_mr) {
643 			rvt_put_mr(qp->s_rdma_mr);
644 			qp->s_rdma_mr = NULL;
645 		}
646 	}
647 
648 	for (n = 0; qp->s_ack_queue && n < rvt_max_atomic(rdi); n++) {
649 		struct rvt_ack_entry *e = &qp->s_ack_queue[n];
650 
651 		if (e->rdma_sge.mr) {
652 			rvt_put_mr(e->rdma_sge.mr);
653 			e->rdma_sge.mr = NULL;
654 		}
655 	}
656 }
657 
658 /**
659  * rvt_swqe_has_lkey - return true if lkey is used by swqe
660  * @wqe: the send wqe
661  * @lkey: the lkey
662  *
663  * Test the swqe for using lkey
664  */
665 static bool rvt_swqe_has_lkey(struct rvt_swqe *wqe, u32 lkey)
666 {
667 	int i;
668 
669 	for (i = 0; i < wqe->wr.num_sge; i++) {
670 		struct rvt_sge *sge = &wqe->sg_list[i];
671 
672 		if (rvt_mr_has_lkey(sge->mr, lkey))
673 			return true;
674 	}
675 	return false;
676 }
677 
678 /**
679  * rvt_qp_sends_has_lkey - return true is qp sends use lkey
680  * @qp: the rvt_qp
681  * @lkey: the lkey
682  */
683 static bool rvt_qp_sends_has_lkey(struct rvt_qp *qp, u32 lkey)
684 {
685 	u32 s_last = qp->s_last;
686 
687 	while (s_last != qp->s_head) {
688 		struct rvt_swqe *wqe = rvt_get_swqe_ptr(qp, s_last);
689 
690 		if (rvt_swqe_has_lkey(wqe, lkey))
691 			return true;
692 
693 		if (++s_last >= qp->s_size)
694 			s_last = 0;
695 	}
696 	if (qp->s_rdma_mr)
697 		if (rvt_mr_has_lkey(qp->s_rdma_mr, lkey))
698 			return true;
699 	return false;
700 }
701 
702 /**
703  * rvt_qp_acks_has_lkey - return true if acks have lkey
704  * @qp: the qp
705  * @lkey: the lkey
706  */
707 static bool rvt_qp_acks_has_lkey(struct rvt_qp *qp, u32 lkey)
708 {
709 	int i;
710 	struct rvt_dev_info *rdi = ib_to_rvt(qp->ibqp.device);
711 
712 	for (i = 0; qp->s_ack_queue && i < rvt_max_atomic(rdi); i++) {
713 		struct rvt_ack_entry *e = &qp->s_ack_queue[i];
714 
715 		if (rvt_mr_has_lkey(e->rdma_sge.mr, lkey))
716 			return true;
717 	}
718 	return false;
719 }
720 
721 /**
722  * rvt_qp_mr_clean - clean up remote ops for lkey
723  * @qp: the qp
724  * @lkey: the lkey that is being de-registered
725  *
726  * This routine checks if the lkey is being used by
727  * the qp.
728  *
729  * If so, the qp is put into an error state to elminate
730  * any references from the qp.
731  */
732 void rvt_qp_mr_clean(struct rvt_qp *qp, u32 lkey)
733 {
734 	bool lastwqe = false;
735 
736 	if (qp->ibqp.qp_type == IB_QPT_SMI ||
737 	    qp->ibqp.qp_type == IB_QPT_GSI)
738 		/* avoid special QPs */
739 		return;
740 	spin_lock_irq(&qp->r_lock);
741 	spin_lock(&qp->s_hlock);
742 	spin_lock(&qp->s_lock);
743 
744 	if (qp->state == IB_QPS_ERR || qp->state == IB_QPS_RESET)
745 		goto check_lwqe;
746 
747 	if (rvt_ss_has_lkey(&qp->r_sge, lkey) ||
748 	    rvt_qp_sends_has_lkey(qp, lkey) ||
749 	    rvt_qp_acks_has_lkey(qp, lkey))
750 		lastwqe = rvt_error_qp(qp, IB_WC_LOC_PROT_ERR);
751 check_lwqe:
752 	spin_unlock(&qp->s_lock);
753 	spin_unlock(&qp->s_hlock);
754 	spin_unlock_irq(&qp->r_lock);
755 	if (lastwqe) {
756 		struct ib_event ev;
757 
758 		ev.device = qp->ibqp.device;
759 		ev.element.qp = &qp->ibqp;
760 		ev.event = IB_EVENT_QP_LAST_WQE_REACHED;
761 		qp->ibqp.event_handler(&ev, qp->ibqp.qp_context);
762 	}
763 }
764 
765 /**
766  * rvt_remove_qp - remove qp form table
767  * @rdi: rvt dev struct
768  * @qp: qp to remove
769  *
770  * Remove the QP from the table so it can't be found asynchronously by
771  * the receive routine.
772  */
773 static void rvt_remove_qp(struct rvt_dev_info *rdi, struct rvt_qp *qp)
774 {
775 	struct rvt_ibport *rvp = rdi->ports[qp->port_num - 1];
776 	u32 n = hash_32(qp->ibqp.qp_num, rdi->qp_dev->qp_table_bits);
777 	unsigned long flags;
778 	int removed = 1;
779 
780 	spin_lock_irqsave(&rdi->qp_dev->qpt_lock, flags);
781 
782 	if (rcu_dereference_protected(rvp->qp[0],
783 			lockdep_is_held(&rdi->qp_dev->qpt_lock)) == qp) {
784 		RCU_INIT_POINTER(rvp->qp[0], NULL);
785 	} else if (rcu_dereference_protected(rvp->qp[1],
786 			lockdep_is_held(&rdi->qp_dev->qpt_lock)) == qp) {
787 		RCU_INIT_POINTER(rvp->qp[1], NULL);
788 	} else {
789 		struct rvt_qp *q;
790 		struct rvt_qp __rcu **qpp;
791 
792 		removed = 0;
793 		qpp = &rdi->qp_dev->qp_table[n];
794 		for (; (q = rcu_dereference_protected(*qpp,
795 			lockdep_is_held(&rdi->qp_dev->qpt_lock))) != NULL;
796 			qpp = &q->next) {
797 			if (q == qp) {
798 				RCU_INIT_POINTER(*qpp,
799 				     rcu_dereference_protected(qp->next,
800 				     lockdep_is_held(&rdi->qp_dev->qpt_lock)));
801 				removed = 1;
802 				trace_rvt_qpremove(qp, n);
803 				break;
804 			}
805 		}
806 	}
807 
808 	spin_unlock_irqrestore(&rdi->qp_dev->qpt_lock, flags);
809 	if (removed) {
810 		synchronize_rcu();
811 		rvt_put_qp(qp);
812 	}
813 }
814 
815 /**
816  * rvt_alloc_rq - allocate memory for user or kernel buffer
817  * @rq: receive queue data structure
818  * @size: number of request queue entries
819  * @node: The NUMA node
820  * @udata: True if user data is available or not false
821  *
822  * Return: If memory allocation failed, return -ENONEM
823  * This function is used by both shared receive
824  * queues and non-shared receive queues to allocate
825  * memory.
826  */
827 int rvt_alloc_rq(struct rvt_rq *rq, u32 size, int node,
828 		 struct ib_udata *udata)
829 {
830 	if (udata) {
831 		rq->wq = vmalloc_user(sizeof(struct rvt_rwq) + size);
832 		if (!rq->wq)
833 			goto bail;
834 		/* need kwq with no buffers */
835 		rq->kwq = kzalloc_node(sizeof(*rq->kwq), GFP_KERNEL, node);
836 		if (!rq->kwq)
837 			goto bail;
838 		rq->kwq->curr_wq = rq->wq->wq;
839 	} else {
840 		/* need kwq with buffers */
841 		rq->kwq =
842 			vzalloc_node(sizeof(struct rvt_krwq) + size, node);
843 		if (!rq->kwq)
844 			goto bail;
845 		rq->kwq->curr_wq = rq->kwq->wq;
846 	}
847 
848 	spin_lock_init(&rq->kwq->p_lock);
849 	spin_lock_init(&rq->kwq->c_lock);
850 	return 0;
851 bail:
852 	rvt_free_rq(rq);
853 	return -ENOMEM;
854 }
855 
856 /**
857  * rvt_init_qp - initialize the QP state to the reset state
858  * @rdi: rvt dev struct
859  * @qp: the QP to init or reinit
860  * @type: the QP type
861  *
862  * This function is called from both rvt_create_qp() and
863  * rvt_reset_qp().   The difference is that the reset
864  * patch the necessary locks to protect against concurent
865  * access.
866  */
867 static void rvt_init_qp(struct rvt_dev_info *rdi, struct rvt_qp *qp,
868 			enum ib_qp_type type)
869 {
870 	qp->remote_qpn = 0;
871 	qp->qkey = 0;
872 	qp->qp_access_flags = 0;
873 	qp->s_flags &= RVT_S_SIGNAL_REQ_WR;
874 	qp->s_hdrwords = 0;
875 	qp->s_wqe = NULL;
876 	qp->s_draining = 0;
877 	qp->s_next_psn = 0;
878 	qp->s_last_psn = 0;
879 	qp->s_sending_psn = 0;
880 	qp->s_sending_hpsn = 0;
881 	qp->s_psn = 0;
882 	qp->r_psn = 0;
883 	qp->r_msn = 0;
884 	if (type == IB_QPT_RC) {
885 		qp->s_state = IB_OPCODE_RC_SEND_LAST;
886 		qp->r_state = IB_OPCODE_RC_SEND_LAST;
887 	} else {
888 		qp->s_state = IB_OPCODE_UC_SEND_LAST;
889 		qp->r_state = IB_OPCODE_UC_SEND_LAST;
890 	}
891 	qp->s_ack_state = IB_OPCODE_RC_ACKNOWLEDGE;
892 	qp->r_nak_state = 0;
893 	qp->r_aflags = 0;
894 	qp->r_flags = 0;
895 	qp->s_head = 0;
896 	qp->s_tail = 0;
897 	qp->s_cur = 0;
898 	qp->s_acked = 0;
899 	qp->s_last = 0;
900 	qp->s_ssn = 1;
901 	qp->s_lsn = 0;
902 	qp->s_mig_state = IB_MIG_MIGRATED;
903 	qp->r_head_ack_queue = 0;
904 	qp->s_tail_ack_queue = 0;
905 	qp->s_acked_ack_queue = 0;
906 	qp->s_num_rd_atomic = 0;
907 	qp->r_sge.num_sge = 0;
908 	atomic_set(&qp->s_reserved_used, 0);
909 }
910 
911 /**
912  * _rvt_reset_qp - initialize the QP state to the reset state
913  * @rdi: rvt dev struct
914  * @qp: the QP to reset
915  * @type: the QP type
916  *
917  * r_lock, s_hlock, and s_lock are required to be held by the caller
918  */
919 static void _rvt_reset_qp(struct rvt_dev_info *rdi, struct rvt_qp *qp,
920 			  enum ib_qp_type type)
921 	__must_hold(&qp->s_lock)
922 	__must_hold(&qp->s_hlock)
923 	__must_hold(&qp->r_lock)
924 {
925 	lockdep_assert_held(&qp->r_lock);
926 	lockdep_assert_held(&qp->s_hlock);
927 	lockdep_assert_held(&qp->s_lock);
928 	if (qp->state != IB_QPS_RESET) {
929 		qp->state = IB_QPS_RESET;
930 
931 		/* Let drivers flush their waitlist */
932 		rdi->driver_f.flush_qp_waiters(qp);
933 		rvt_stop_rc_timers(qp);
934 		qp->s_flags &= ~(RVT_S_TIMER | RVT_S_ANY_WAIT);
935 		spin_unlock(&qp->s_lock);
936 		spin_unlock(&qp->s_hlock);
937 		spin_unlock_irq(&qp->r_lock);
938 
939 		/* Stop the send queue and the retry timer */
940 		rdi->driver_f.stop_send_queue(qp);
941 		rvt_del_timers_sync(qp);
942 		/* Wait for things to stop */
943 		rdi->driver_f.quiesce_qp(qp);
944 
945 		/* take qp out the hash and wait for it to be unused */
946 		rvt_remove_qp(rdi, qp);
947 
948 		/* grab the lock b/c it was locked at call time */
949 		spin_lock_irq(&qp->r_lock);
950 		spin_lock(&qp->s_hlock);
951 		spin_lock(&qp->s_lock);
952 
953 		rvt_clear_mr_refs(qp, 1);
954 		/*
955 		 * Let the driver do any tear down or re-init it needs to for
956 		 * a qp that has been reset
957 		 */
958 		rdi->driver_f.notify_qp_reset(qp);
959 	}
960 	rvt_init_qp(rdi, qp, type);
961 	lockdep_assert_held(&qp->r_lock);
962 	lockdep_assert_held(&qp->s_hlock);
963 	lockdep_assert_held(&qp->s_lock);
964 }
965 
966 /**
967  * rvt_reset_qp - initialize the QP state to the reset state
968  * @rdi: the device info
969  * @qp: the QP to reset
970  * @type: the QP type
971  *
972  * This is the wrapper function to acquire the r_lock, s_hlock, and s_lock
973  * before calling _rvt_reset_qp().
974  */
975 static void rvt_reset_qp(struct rvt_dev_info *rdi, struct rvt_qp *qp,
976 			 enum ib_qp_type type)
977 {
978 	spin_lock_irq(&qp->r_lock);
979 	spin_lock(&qp->s_hlock);
980 	spin_lock(&qp->s_lock);
981 	_rvt_reset_qp(rdi, qp, type);
982 	spin_unlock(&qp->s_lock);
983 	spin_unlock(&qp->s_hlock);
984 	spin_unlock_irq(&qp->r_lock);
985 }
986 
987 /** rvt_free_qpn - Free a qpn from the bit map
988  * @qpt: QP table
989  * @qpn: queue pair number to free
990  */
991 static void rvt_free_qpn(struct rvt_qpn_table *qpt, u32 qpn)
992 {
993 	struct rvt_qpn_map *map;
994 
995 	if ((qpn & RVT_AIP_QP_PREFIX_MASK) == RVT_AIP_QP_BASE)
996 		qpn &= RVT_AIP_QP_SUFFIX;
997 
998 	map = qpt->map + (qpn & RVT_QPN_MASK) / RVT_BITS_PER_PAGE;
999 	if (map->page)
1000 		clear_bit(qpn & RVT_BITS_PER_PAGE_MASK, map->page);
1001 }
1002 
1003 /**
1004  * get_allowed_ops - Given a QP type return the appropriate allowed OP
1005  * @type: valid, supported, QP type
1006  */
1007 static u8 get_allowed_ops(enum ib_qp_type type)
1008 {
1009 	return type == IB_QPT_RC ? IB_OPCODE_RC : type == IB_QPT_UC ?
1010 		IB_OPCODE_UC : IB_OPCODE_UD;
1011 }
1012 
1013 /**
1014  * free_ud_wq_attr - Clean up AH attribute cache for UD QPs
1015  * @qp: Valid QP with allowed_ops set
1016  *
1017  * The rvt_swqe data structure being used is a union, so this is
1018  * only valid for UD QPs.
1019  */
1020 static void free_ud_wq_attr(struct rvt_qp *qp)
1021 {
1022 	struct rvt_swqe *wqe;
1023 	int i;
1024 
1025 	for (i = 0; qp->allowed_ops == IB_OPCODE_UD && i < qp->s_size; i++) {
1026 		wqe = rvt_get_swqe_ptr(qp, i);
1027 		kfree(wqe->ud_wr.attr);
1028 		wqe->ud_wr.attr = NULL;
1029 	}
1030 }
1031 
1032 /**
1033  * alloc_ud_wq_attr - AH attribute cache for UD QPs
1034  * @qp: Valid QP with allowed_ops set
1035  * @node: Numa node for allocation
1036  *
1037  * The rvt_swqe data structure being used is a union, so this is
1038  * only valid for UD QPs.
1039  */
1040 static int alloc_ud_wq_attr(struct rvt_qp *qp, int node)
1041 {
1042 	struct rvt_swqe *wqe;
1043 	int i;
1044 
1045 	for (i = 0; qp->allowed_ops == IB_OPCODE_UD && i < qp->s_size; i++) {
1046 		wqe = rvt_get_swqe_ptr(qp, i);
1047 		wqe->ud_wr.attr = kzalloc_node(sizeof(*wqe->ud_wr.attr),
1048 					       GFP_KERNEL, node);
1049 		if (!wqe->ud_wr.attr) {
1050 			free_ud_wq_attr(qp);
1051 			return -ENOMEM;
1052 		}
1053 	}
1054 
1055 	return 0;
1056 }
1057 
1058 /**
1059  * rvt_create_qp - create a queue pair for a device
1060  * @ibpd: the protection domain who's device we create the queue pair for
1061  * @init_attr: the attributes of the queue pair
1062  * @udata: user data for libibverbs.so
1063  *
1064  * Queue pair creation is mostly an rvt issue. However, drivers have their own
1065  * unique idea of what queue pair numbers mean. For instance there is a reserved
1066  * range for PSM.
1067  *
1068  * Return: the queue pair on success, otherwise returns an errno.
1069  *
1070  * Called by the ib_create_qp() core verbs function.
1071  */
1072 struct ib_qp *rvt_create_qp(struct ib_pd *ibpd,
1073 			    struct ib_qp_init_attr *init_attr,
1074 			    struct ib_udata *udata)
1075 {
1076 	struct rvt_qp *qp;
1077 	int err;
1078 	struct rvt_swqe *swq = NULL;
1079 	size_t sz;
1080 	size_t sg_list_sz;
1081 	struct ib_qp *ret = ERR_PTR(-ENOMEM);
1082 	struct rvt_dev_info *rdi = ib_to_rvt(ibpd->device);
1083 	void *priv = NULL;
1084 	size_t sqsize;
1085 	u8 exclude_prefix = 0;
1086 
1087 	if (!rdi)
1088 		return ERR_PTR(-EINVAL);
1089 
1090 	if (init_attr->create_flags & ~IB_QP_CREATE_NETDEV_USE)
1091 		return ERR_PTR(-EOPNOTSUPP);
1092 
1093 	if (init_attr->cap.max_send_sge > rdi->dparms.props.max_send_sge ||
1094 	    init_attr->cap.max_send_wr > rdi->dparms.props.max_qp_wr)
1095 		return ERR_PTR(-EINVAL);
1096 
1097 	/* Check receive queue parameters if no SRQ is specified. */
1098 	if (!init_attr->srq) {
1099 		if (init_attr->cap.max_recv_sge >
1100 		    rdi->dparms.props.max_recv_sge ||
1101 		    init_attr->cap.max_recv_wr > rdi->dparms.props.max_qp_wr)
1102 			return ERR_PTR(-EINVAL);
1103 
1104 		if (init_attr->cap.max_send_sge +
1105 		    init_attr->cap.max_send_wr +
1106 		    init_attr->cap.max_recv_sge +
1107 		    init_attr->cap.max_recv_wr == 0)
1108 			return ERR_PTR(-EINVAL);
1109 	}
1110 	sqsize =
1111 		init_attr->cap.max_send_wr + 1 +
1112 		rdi->dparms.reserved_operations;
1113 	switch (init_attr->qp_type) {
1114 	case IB_QPT_SMI:
1115 	case IB_QPT_GSI:
1116 		if (init_attr->port_num == 0 ||
1117 		    init_attr->port_num > ibpd->device->phys_port_cnt)
1118 			return ERR_PTR(-EINVAL);
1119 		fallthrough;
1120 	case IB_QPT_UC:
1121 	case IB_QPT_RC:
1122 	case IB_QPT_UD:
1123 		sz = struct_size(swq, sg_list, init_attr->cap.max_send_sge);
1124 		swq = vzalloc_node(array_size(sz, sqsize), rdi->dparms.node);
1125 		if (!swq)
1126 			return ERR_PTR(-ENOMEM);
1127 
1128 		sz = sizeof(*qp);
1129 		sg_list_sz = 0;
1130 		if (init_attr->srq) {
1131 			struct rvt_srq *srq = ibsrq_to_rvtsrq(init_attr->srq);
1132 
1133 			if (srq->rq.max_sge > 1)
1134 				sg_list_sz = sizeof(*qp->r_sg_list) *
1135 					(srq->rq.max_sge - 1);
1136 		} else if (init_attr->cap.max_recv_sge > 1)
1137 			sg_list_sz = sizeof(*qp->r_sg_list) *
1138 				(init_attr->cap.max_recv_sge - 1);
1139 		qp = kzalloc_node(sz + sg_list_sz, GFP_KERNEL,
1140 				  rdi->dparms.node);
1141 		if (!qp)
1142 			goto bail_swq;
1143 		qp->allowed_ops = get_allowed_ops(init_attr->qp_type);
1144 
1145 		RCU_INIT_POINTER(qp->next, NULL);
1146 		if (init_attr->qp_type == IB_QPT_RC) {
1147 			qp->s_ack_queue =
1148 				kcalloc_node(rvt_max_atomic(rdi),
1149 					     sizeof(*qp->s_ack_queue),
1150 					     GFP_KERNEL,
1151 					     rdi->dparms.node);
1152 			if (!qp->s_ack_queue)
1153 				goto bail_qp;
1154 		}
1155 		/* initialize timers needed for rc qp */
1156 		timer_setup(&qp->s_timer, rvt_rc_timeout, 0);
1157 		hrtimer_init(&qp->s_rnr_timer, CLOCK_MONOTONIC,
1158 			     HRTIMER_MODE_REL);
1159 		qp->s_rnr_timer.function = rvt_rc_rnr_retry;
1160 
1161 		/*
1162 		 * Driver needs to set up it's private QP structure and do any
1163 		 * initialization that is needed.
1164 		 */
1165 		priv = rdi->driver_f.qp_priv_alloc(rdi, qp);
1166 		if (IS_ERR(priv)) {
1167 			ret = priv;
1168 			goto bail_qp;
1169 		}
1170 		qp->priv = priv;
1171 		qp->timeout_jiffies =
1172 			usecs_to_jiffies((4096UL * (1UL << qp->timeout)) /
1173 				1000UL);
1174 		if (init_attr->srq) {
1175 			sz = 0;
1176 		} else {
1177 			qp->r_rq.size = init_attr->cap.max_recv_wr + 1;
1178 			qp->r_rq.max_sge = init_attr->cap.max_recv_sge;
1179 			sz = (sizeof(struct ib_sge) * qp->r_rq.max_sge) +
1180 				sizeof(struct rvt_rwqe);
1181 			err = rvt_alloc_rq(&qp->r_rq, qp->r_rq.size * sz,
1182 					   rdi->dparms.node, udata);
1183 			if (err) {
1184 				ret = ERR_PTR(err);
1185 				goto bail_driver_priv;
1186 			}
1187 		}
1188 
1189 		/*
1190 		 * ib_create_qp() will initialize qp->ibqp
1191 		 * except for qp->ibqp.qp_num.
1192 		 */
1193 		spin_lock_init(&qp->r_lock);
1194 		spin_lock_init(&qp->s_hlock);
1195 		spin_lock_init(&qp->s_lock);
1196 		atomic_set(&qp->refcount, 0);
1197 		atomic_set(&qp->local_ops_pending, 0);
1198 		init_waitqueue_head(&qp->wait);
1199 		INIT_LIST_HEAD(&qp->rspwait);
1200 		qp->state = IB_QPS_RESET;
1201 		qp->s_wq = swq;
1202 		qp->s_size = sqsize;
1203 		qp->s_avail = init_attr->cap.max_send_wr;
1204 		qp->s_max_sge = init_attr->cap.max_send_sge;
1205 		if (init_attr->sq_sig_type == IB_SIGNAL_REQ_WR)
1206 			qp->s_flags = RVT_S_SIGNAL_REQ_WR;
1207 		err = alloc_ud_wq_attr(qp, rdi->dparms.node);
1208 		if (err) {
1209 			ret = (ERR_PTR(err));
1210 			goto bail_rq_rvt;
1211 		}
1212 
1213 		if (init_attr->create_flags & IB_QP_CREATE_NETDEV_USE)
1214 			exclude_prefix = RVT_AIP_QP_PREFIX;
1215 
1216 		err = alloc_qpn(rdi, &rdi->qp_dev->qpn_table,
1217 				init_attr->qp_type,
1218 				init_attr->port_num,
1219 				exclude_prefix);
1220 		if (err < 0) {
1221 			ret = ERR_PTR(err);
1222 			goto bail_rq_wq;
1223 		}
1224 		qp->ibqp.qp_num = err;
1225 		if (init_attr->create_flags & IB_QP_CREATE_NETDEV_USE)
1226 			qp->ibqp.qp_num |= RVT_AIP_QP_BASE;
1227 		qp->port_num = init_attr->port_num;
1228 		rvt_init_qp(rdi, qp, init_attr->qp_type);
1229 		if (rdi->driver_f.qp_priv_init) {
1230 			err = rdi->driver_f.qp_priv_init(rdi, qp, init_attr);
1231 			if (err) {
1232 				ret = ERR_PTR(err);
1233 				goto bail_rq_wq;
1234 			}
1235 		}
1236 		break;
1237 
1238 	default:
1239 		/* Don't support raw QPs */
1240 		return ERR_PTR(-EOPNOTSUPP);
1241 	}
1242 
1243 	init_attr->cap.max_inline_data = 0;
1244 
1245 	/*
1246 	 * Return the address of the RWQ as the offset to mmap.
1247 	 * See rvt_mmap() for details.
1248 	 */
1249 	if (udata && udata->outlen >= sizeof(__u64)) {
1250 		if (!qp->r_rq.wq) {
1251 			__u64 offset = 0;
1252 
1253 			err = ib_copy_to_udata(udata, &offset,
1254 					       sizeof(offset));
1255 			if (err) {
1256 				ret = ERR_PTR(err);
1257 				goto bail_qpn;
1258 			}
1259 		} else {
1260 			u32 s = sizeof(struct rvt_rwq) + qp->r_rq.size * sz;
1261 
1262 			qp->ip = rvt_create_mmap_info(rdi, s, udata,
1263 						      qp->r_rq.wq);
1264 			if (IS_ERR(qp->ip)) {
1265 				ret = ERR_CAST(qp->ip);
1266 				goto bail_qpn;
1267 			}
1268 
1269 			err = ib_copy_to_udata(udata, &qp->ip->offset,
1270 					       sizeof(qp->ip->offset));
1271 			if (err) {
1272 				ret = ERR_PTR(err);
1273 				goto bail_ip;
1274 			}
1275 		}
1276 		qp->pid = current->pid;
1277 	}
1278 
1279 	spin_lock(&rdi->n_qps_lock);
1280 	if (rdi->n_qps_allocated == rdi->dparms.props.max_qp) {
1281 		spin_unlock(&rdi->n_qps_lock);
1282 		ret = ERR_PTR(-ENOMEM);
1283 		goto bail_ip;
1284 	}
1285 
1286 	rdi->n_qps_allocated++;
1287 	/*
1288 	 * Maintain a busy_jiffies variable that will be added to the timeout
1289 	 * period in mod_retry_timer and add_retry_timer. This busy jiffies
1290 	 * is scaled by the number of rc qps created for the device to reduce
1291 	 * the number of timeouts occurring when there is a large number of
1292 	 * qps. busy_jiffies is incremented every rc qp scaling interval.
1293 	 * The scaling interval is selected based on extensive performance
1294 	 * evaluation of targeted workloads.
1295 	 */
1296 	if (init_attr->qp_type == IB_QPT_RC) {
1297 		rdi->n_rc_qps++;
1298 		rdi->busy_jiffies = rdi->n_rc_qps / RC_QP_SCALING_INTERVAL;
1299 	}
1300 	spin_unlock(&rdi->n_qps_lock);
1301 
1302 	if (qp->ip) {
1303 		spin_lock_irq(&rdi->pending_lock);
1304 		list_add(&qp->ip->pending_mmaps, &rdi->pending_mmaps);
1305 		spin_unlock_irq(&rdi->pending_lock);
1306 	}
1307 
1308 	ret = &qp->ibqp;
1309 
1310 	return ret;
1311 
1312 bail_ip:
1313 	if (qp->ip)
1314 		kref_put(&qp->ip->ref, rvt_release_mmap_info);
1315 
1316 bail_qpn:
1317 	rvt_free_qpn(&rdi->qp_dev->qpn_table, qp->ibqp.qp_num);
1318 
1319 bail_rq_wq:
1320 	free_ud_wq_attr(qp);
1321 
1322 bail_rq_rvt:
1323 	rvt_free_rq(&qp->r_rq);
1324 
1325 bail_driver_priv:
1326 	rdi->driver_f.qp_priv_free(rdi, qp);
1327 
1328 bail_qp:
1329 	kfree(qp->s_ack_queue);
1330 	kfree(qp);
1331 
1332 bail_swq:
1333 	vfree(swq);
1334 
1335 	return ret;
1336 }
1337 
1338 /**
1339  * rvt_error_qp - put a QP into the error state
1340  * @qp: the QP to put into the error state
1341  * @err: the receive completion error to signal if a RWQE is active
1342  *
1343  * Flushes both send and receive work queues.
1344  *
1345  * Return: true if last WQE event should be generated.
1346  * The QP r_lock and s_lock should be held and interrupts disabled.
1347  * If we are already in error state, just return.
1348  */
1349 int rvt_error_qp(struct rvt_qp *qp, enum ib_wc_status err)
1350 {
1351 	struct ib_wc wc;
1352 	int ret = 0;
1353 	struct rvt_dev_info *rdi = ib_to_rvt(qp->ibqp.device);
1354 
1355 	lockdep_assert_held(&qp->r_lock);
1356 	lockdep_assert_held(&qp->s_lock);
1357 	if (qp->state == IB_QPS_ERR || qp->state == IB_QPS_RESET)
1358 		goto bail;
1359 
1360 	qp->state = IB_QPS_ERR;
1361 
1362 	if (qp->s_flags & (RVT_S_TIMER | RVT_S_WAIT_RNR)) {
1363 		qp->s_flags &= ~(RVT_S_TIMER | RVT_S_WAIT_RNR);
1364 		del_timer(&qp->s_timer);
1365 	}
1366 
1367 	if (qp->s_flags & RVT_S_ANY_WAIT_SEND)
1368 		qp->s_flags &= ~RVT_S_ANY_WAIT_SEND;
1369 
1370 	rdi->driver_f.notify_error_qp(qp);
1371 
1372 	/* Schedule the sending tasklet to drain the send work queue. */
1373 	if (READ_ONCE(qp->s_last) != qp->s_head)
1374 		rdi->driver_f.schedule_send(qp);
1375 
1376 	rvt_clear_mr_refs(qp, 0);
1377 
1378 	memset(&wc, 0, sizeof(wc));
1379 	wc.qp = &qp->ibqp;
1380 	wc.opcode = IB_WC_RECV;
1381 
1382 	if (test_and_clear_bit(RVT_R_WRID_VALID, &qp->r_aflags)) {
1383 		wc.wr_id = qp->r_wr_id;
1384 		wc.status = err;
1385 		rvt_cq_enter(ibcq_to_rvtcq(qp->ibqp.recv_cq), &wc, 1);
1386 	}
1387 	wc.status = IB_WC_WR_FLUSH_ERR;
1388 
1389 	if (qp->r_rq.kwq) {
1390 		u32 head;
1391 		u32 tail;
1392 		struct rvt_rwq *wq = NULL;
1393 		struct rvt_krwq *kwq = NULL;
1394 
1395 		spin_lock(&qp->r_rq.kwq->c_lock);
1396 		/* qp->ip used to validate if there is a  user buffer mmaped */
1397 		if (qp->ip) {
1398 			wq = qp->r_rq.wq;
1399 			head = RDMA_READ_UAPI_ATOMIC(wq->head);
1400 			tail = RDMA_READ_UAPI_ATOMIC(wq->tail);
1401 		} else {
1402 			kwq = qp->r_rq.kwq;
1403 			head = kwq->head;
1404 			tail = kwq->tail;
1405 		}
1406 		/* sanity check pointers before trusting them */
1407 		if (head >= qp->r_rq.size)
1408 			head = 0;
1409 		if (tail >= qp->r_rq.size)
1410 			tail = 0;
1411 		while (tail != head) {
1412 			wc.wr_id = rvt_get_rwqe_ptr(&qp->r_rq, tail)->wr_id;
1413 			if (++tail >= qp->r_rq.size)
1414 				tail = 0;
1415 			rvt_cq_enter(ibcq_to_rvtcq(qp->ibqp.recv_cq), &wc, 1);
1416 		}
1417 		if (qp->ip)
1418 			RDMA_WRITE_UAPI_ATOMIC(wq->tail, tail);
1419 		else
1420 			kwq->tail = tail;
1421 		spin_unlock(&qp->r_rq.kwq->c_lock);
1422 	} else if (qp->ibqp.event_handler) {
1423 		ret = 1;
1424 	}
1425 
1426 bail:
1427 	return ret;
1428 }
1429 EXPORT_SYMBOL(rvt_error_qp);
1430 
1431 /*
1432  * Put the QP into the hash table.
1433  * The hash table holds a reference to the QP.
1434  */
1435 static void rvt_insert_qp(struct rvt_dev_info *rdi, struct rvt_qp *qp)
1436 {
1437 	struct rvt_ibport *rvp = rdi->ports[qp->port_num - 1];
1438 	unsigned long flags;
1439 
1440 	rvt_get_qp(qp);
1441 	spin_lock_irqsave(&rdi->qp_dev->qpt_lock, flags);
1442 
1443 	if (qp->ibqp.qp_num <= 1) {
1444 		rcu_assign_pointer(rvp->qp[qp->ibqp.qp_num], qp);
1445 	} else {
1446 		u32 n = hash_32(qp->ibqp.qp_num, rdi->qp_dev->qp_table_bits);
1447 
1448 		qp->next = rdi->qp_dev->qp_table[n];
1449 		rcu_assign_pointer(rdi->qp_dev->qp_table[n], qp);
1450 		trace_rvt_qpinsert(qp, n);
1451 	}
1452 
1453 	spin_unlock_irqrestore(&rdi->qp_dev->qpt_lock, flags);
1454 }
1455 
1456 /**
1457  * rvt_modify_qp - modify the attributes of a queue pair
1458  * @ibqp: the queue pair who's attributes we're modifying
1459  * @attr: the new attributes
1460  * @attr_mask: the mask of attributes to modify
1461  * @udata: user data for libibverbs.so
1462  *
1463  * Return: 0 on success, otherwise returns an errno.
1464  */
1465 int rvt_modify_qp(struct ib_qp *ibqp, struct ib_qp_attr *attr,
1466 		  int attr_mask, struct ib_udata *udata)
1467 {
1468 	struct rvt_dev_info *rdi = ib_to_rvt(ibqp->device);
1469 	struct rvt_qp *qp = ibqp_to_rvtqp(ibqp);
1470 	enum ib_qp_state cur_state, new_state;
1471 	struct ib_event ev;
1472 	int lastwqe = 0;
1473 	int mig = 0;
1474 	int pmtu = 0; /* for gcc warning only */
1475 	int opa_ah;
1476 
1477 	if (attr_mask & ~IB_QP_ATTR_STANDARD_BITS)
1478 		return -EOPNOTSUPP;
1479 
1480 	spin_lock_irq(&qp->r_lock);
1481 	spin_lock(&qp->s_hlock);
1482 	spin_lock(&qp->s_lock);
1483 
1484 	cur_state = attr_mask & IB_QP_CUR_STATE ?
1485 		attr->cur_qp_state : qp->state;
1486 	new_state = attr_mask & IB_QP_STATE ? attr->qp_state : cur_state;
1487 	opa_ah = rdma_cap_opa_ah(ibqp->device, qp->port_num);
1488 
1489 	if (!ib_modify_qp_is_ok(cur_state, new_state, ibqp->qp_type,
1490 				attr_mask))
1491 		goto inval;
1492 
1493 	if (rdi->driver_f.check_modify_qp &&
1494 	    rdi->driver_f.check_modify_qp(qp, attr, attr_mask, udata))
1495 		goto inval;
1496 
1497 	if (attr_mask & IB_QP_AV) {
1498 		if (opa_ah) {
1499 			if (rdma_ah_get_dlid(&attr->ah_attr) >=
1500 				opa_get_mcast_base(OPA_MCAST_NR))
1501 				goto inval;
1502 		} else {
1503 			if (rdma_ah_get_dlid(&attr->ah_attr) >=
1504 				be16_to_cpu(IB_MULTICAST_LID_BASE))
1505 				goto inval;
1506 		}
1507 
1508 		if (rvt_check_ah(qp->ibqp.device, &attr->ah_attr))
1509 			goto inval;
1510 	}
1511 
1512 	if (attr_mask & IB_QP_ALT_PATH) {
1513 		if (opa_ah) {
1514 			if (rdma_ah_get_dlid(&attr->alt_ah_attr) >=
1515 				opa_get_mcast_base(OPA_MCAST_NR))
1516 				goto inval;
1517 		} else {
1518 			if (rdma_ah_get_dlid(&attr->alt_ah_attr) >=
1519 				be16_to_cpu(IB_MULTICAST_LID_BASE))
1520 				goto inval;
1521 		}
1522 
1523 		if (rvt_check_ah(qp->ibqp.device, &attr->alt_ah_attr))
1524 			goto inval;
1525 		if (attr->alt_pkey_index >= rvt_get_npkeys(rdi))
1526 			goto inval;
1527 	}
1528 
1529 	if (attr_mask & IB_QP_PKEY_INDEX)
1530 		if (attr->pkey_index >= rvt_get_npkeys(rdi))
1531 			goto inval;
1532 
1533 	if (attr_mask & IB_QP_MIN_RNR_TIMER)
1534 		if (attr->min_rnr_timer > 31)
1535 			goto inval;
1536 
1537 	if (attr_mask & IB_QP_PORT)
1538 		if (qp->ibqp.qp_type == IB_QPT_SMI ||
1539 		    qp->ibqp.qp_type == IB_QPT_GSI ||
1540 		    attr->port_num == 0 ||
1541 		    attr->port_num > ibqp->device->phys_port_cnt)
1542 			goto inval;
1543 
1544 	if (attr_mask & IB_QP_DEST_QPN)
1545 		if (attr->dest_qp_num > RVT_QPN_MASK)
1546 			goto inval;
1547 
1548 	if (attr_mask & IB_QP_RETRY_CNT)
1549 		if (attr->retry_cnt > 7)
1550 			goto inval;
1551 
1552 	if (attr_mask & IB_QP_RNR_RETRY)
1553 		if (attr->rnr_retry > 7)
1554 			goto inval;
1555 
1556 	/*
1557 	 * Don't allow invalid path_mtu values.  OK to set greater
1558 	 * than the active mtu (or even the max_cap, if we have tuned
1559 	 * that to a small mtu.  We'll set qp->path_mtu
1560 	 * to the lesser of requested attribute mtu and active,
1561 	 * for packetizing messages.
1562 	 * Note that the QP port has to be set in INIT and MTU in RTR.
1563 	 */
1564 	if (attr_mask & IB_QP_PATH_MTU) {
1565 		pmtu = rdi->driver_f.get_pmtu_from_attr(rdi, qp, attr);
1566 		if (pmtu < 0)
1567 			goto inval;
1568 	}
1569 
1570 	if (attr_mask & IB_QP_PATH_MIG_STATE) {
1571 		if (attr->path_mig_state == IB_MIG_REARM) {
1572 			if (qp->s_mig_state == IB_MIG_ARMED)
1573 				goto inval;
1574 			if (new_state != IB_QPS_RTS)
1575 				goto inval;
1576 		} else if (attr->path_mig_state == IB_MIG_MIGRATED) {
1577 			if (qp->s_mig_state == IB_MIG_REARM)
1578 				goto inval;
1579 			if (new_state != IB_QPS_RTS && new_state != IB_QPS_SQD)
1580 				goto inval;
1581 			if (qp->s_mig_state == IB_MIG_ARMED)
1582 				mig = 1;
1583 		} else {
1584 			goto inval;
1585 		}
1586 	}
1587 
1588 	if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC)
1589 		if (attr->max_dest_rd_atomic > rdi->dparms.max_rdma_atomic)
1590 			goto inval;
1591 
1592 	switch (new_state) {
1593 	case IB_QPS_RESET:
1594 		if (qp->state != IB_QPS_RESET)
1595 			_rvt_reset_qp(rdi, qp, ibqp->qp_type);
1596 		break;
1597 
1598 	case IB_QPS_RTR:
1599 		/* Allow event to re-trigger if QP set to RTR more than once */
1600 		qp->r_flags &= ~RVT_R_COMM_EST;
1601 		qp->state = new_state;
1602 		break;
1603 
1604 	case IB_QPS_SQD:
1605 		qp->s_draining = qp->s_last != qp->s_cur;
1606 		qp->state = new_state;
1607 		break;
1608 
1609 	case IB_QPS_SQE:
1610 		if (qp->ibqp.qp_type == IB_QPT_RC)
1611 			goto inval;
1612 		qp->state = new_state;
1613 		break;
1614 
1615 	case IB_QPS_ERR:
1616 		lastwqe = rvt_error_qp(qp, IB_WC_WR_FLUSH_ERR);
1617 		break;
1618 
1619 	default:
1620 		qp->state = new_state;
1621 		break;
1622 	}
1623 
1624 	if (attr_mask & IB_QP_PKEY_INDEX)
1625 		qp->s_pkey_index = attr->pkey_index;
1626 
1627 	if (attr_mask & IB_QP_PORT)
1628 		qp->port_num = attr->port_num;
1629 
1630 	if (attr_mask & IB_QP_DEST_QPN)
1631 		qp->remote_qpn = attr->dest_qp_num;
1632 
1633 	if (attr_mask & IB_QP_SQ_PSN) {
1634 		qp->s_next_psn = attr->sq_psn & rdi->dparms.psn_modify_mask;
1635 		qp->s_psn = qp->s_next_psn;
1636 		qp->s_sending_psn = qp->s_next_psn;
1637 		qp->s_last_psn = qp->s_next_psn - 1;
1638 		qp->s_sending_hpsn = qp->s_last_psn;
1639 	}
1640 
1641 	if (attr_mask & IB_QP_RQ_PSN)
1642 		qp->r_psn = attr->rq_psn & rdi->dparms.psn_modify_mask;
1643 
1644 	if (attr_mask & IB_QP_ACCESS_FLAGS)
1645 		qp->qp_access_flags = attr->qp_access_flags;
1646 
1647 	if (attr_mask & IB_QP_AV) {
1648 		rdma_replace_ah_attr(&qp->remote_ah_attr, &attr->ah_attr);
1649 		qp->s_srate = rdma_ah_get_static_rate(&attr->ah_attr);
1650 		qp->srate_mbps = ib_rate_to_mbps(qp->s_srate);
1651 	}
1652 
1653 	if (attr_mask & IB_QP_ALT_PATH) {
1654 		rdma_replace_ah_attr(&qp->alt_ah_attr, &attr->alt_ah_attr);
1655 		qp->s_alt_pkey_index = attr->alt_pkey_index;
1656 	}
1657 
1658 	if (attr_mask & IB_QP_PATH_MIG_STATE) {
1659 		qp->s_mig_state = attr->path_mig_state;
1660 		if (mig) {
1661 			qp->remote_ah_attr = qp->alt_ah_attr;
1662 			qp->port_num = rdma_ah_get_port_num(&qp->alt_ah_attr);
1663 			qp->s_pkey_index = qp->s_alt_pkey_index;
1664 		}
1665 	}
1666 
1667 	if (attr_mask & IB_QP_PATH_MTU) {
1668 		qp->pmtu = rdi->driver_f.mtu_from_qp(rdi, qp, pmtu);
1669 		qp->log_pmtu = ilog2(qp->pmtu);
1670 	}
1671 
1672 	if (attr_mask & IB_QP_RETRY_CNT) {
1673 		qp->s_retry_cnt = attr->retry_cnt;
1674 		qp->s_retry = attr->retry_cnt;
1675 	}
1676 
1677 	if (attr_mask & IB_QP_RNR_RETRY) {
1678 		qp->s_rnr_retry_cnt = attr->rnr_retry;
1679 		qp->s_rnr_retry = attr->rnr_retry;
1680 	}
1681 
1682 	if (attr_mask & IB_QP_MIN_RNR_TIMER)
1683 		qp->r_min_rnr_timer = attr->min_rnr_timer;
1684 
1685 	if (attr_mask & IB_QP_TIMEOUT) {
1686 		qp->timeout = attr->timeout;
1687 		qp->timeout_jiffies = rvt_timeout_to_jiffies(qp->timeout);
1688 	}
1689 
1690 	if (attr_mask & IB_QP_QKEY)
1691 		qp->qkey = attr->qkey;
1692 
1693 	if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC)
1694 		qp->r_max_rd_atomic = attr->max_dest_rd_atomic;
1695 
1696 	if (attr_mask & IB_QP_MAX_QP_RD_ATOMIC)
1697 		qp->s_max_rd_atomic = attr->max_rd_atomic;
1698 
1699 	if (rdi->driver_f.modify_qp)
1700 		rdi->driver_f.modify_qp(qp, attr, attr_mask, udata);
1701 
1702 	spin_unlock(&qp->s_lock);
1703 	spin_unlock(&qp->s_hlock);
1704 	spin_unlock_irq(&qp->r_lock);
1705 
1706 	if (cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT)
1707 		rvt_insert_qp(rdi, qp);
1708 
1709 	if (lastwqe) {
1710 		ev.device = qp->ibqp.device;
1711 		ev.element.qp = &qp->ibqp;
1712 		ev.event = IB_EVENT_QP_LAST_WQE_REACHED;
1713 		qp->ibqp.event_handler(&ev, qp->ibqp.qp_context);
1714 	}
1715 	if (mig) {
1716 		ev.device = qp->ibqp.device;
1717 		ev.element.qp = &qp->ibqp;
1718 		ev.event = IB_EVENT_PATH_MIG;
1719 		qp->ibqp.event_handler(&ev, qp->ibqp.qp_context);
1720 	}
1721 	return 0;
1722 
1723 inval:
1724 	spin_unlock(&qp->s_lock);
1725 	spin_unlock(&qp->s_hlock);
1726 	spin_unlock_irq(&qp->r_lock);
1727 	return -EINVAL;
1728 }
1729 
1730 /**
1731  * rvt_destroy_qp - destroy a queue pair
1732  * @ibqp: the queue pair to destroy
1733  * @udata: unused by the driver
1734  *
1735  * Note that this can be called while the QP is actively sending or
1736  * receiving!
1737  *
1738  * Return: 0 on success.
1739  */
1740 int rvt_destroy_qp(struct ib_qp *ibqp, struct ib_udata *udata)
1741 {
1742 	struct rvt_qp *qp = ibqp_to_rvtqp(ibqp);
1743 	struct rvt_dev_info *rdi = ib_to_rvt(ibqp->device);
1744 
1745 	rvt_reset_qp(rdi, qp, ibqp->qp_type);
1746 
1747 	wait_event(qp->wait, !atomic_read(&qp->refcount));
1748 	/* qpn is now available for use again */
1749 	rvt_free_qpn(&rdi->qp_dev->qpn_table, qp->ibqp.qp_num);
1750 
1751 	spin_lock(&rdi->n_qps_lock);
1752 	rdi->n_qps_allocated--;
1753 	if (qp->ibqp.qp_type == IB_QPT_RC) {
1754 		rdi->n_rc_qps--;
1755 		rdi->busy_jiffies = rdi->n_rc_qps / RC_QP_SCALING_INTERVAL;
1756 	}
1757 	spin_unlock(&rdi->n_qps_lock);
1758 
1759 	if (qp->ip)
1760 		kref_put(&qp->ip->ref, rvt_release_mmap_info);
1761 	kvfree(qp->r_rq.kwq);
1762 	rdi->driver_f.qp_priv_free(rdi, qp);
1763 	kfree(qp->s_ack_queue);
1764 	rdma_destroy_ah_attr(&qp->remote_ah_attr);
1765 	rdma_destroy_ah_attr(&qp->alt_ah_attr);
1766 	free_ud_wq_attr(qp);
1767 	vfree(qp->s_wq);
1768 	kfree(qp);
1769 	return 0;
1770 }
1771 
1772 /**
1773  * rvt_query_qp - query an ipbq
1774  * @ibqp: IB qp to query
1775  * @attr: attr struct to fill in
1776  * @attr_mask: attr mask ignored
1777  * @init_attr: struct to fill in
1778  *
1779  * Return: always 0
1780  */
1781 int rvt_query_qp(struct ib_qp *ibqp, struct ib_qp_attr *attr,
1782 		 int attr_mask, struct ib_qp_init_attr *init_attr)
1783 {
1784 	struct rvt_qp *qp = ibqp_to_rvtqp(ibqp);
1785 	struct rvt_dev_info *rdi = ib_to_rvt(ibqp->device);
1786 
1787 	attr->qp_state = qp->state;
1788 	attr->cur_qp_state = attr->qp_state;
1789 	attr->path_mtu = rdi->driver_f.mtu_to_path_mtu(qp->pmtu);
1790 	attr->path_mig_state = qp->s_mig_state;
1791 	attr->qkey = qp->qkey;
1792 	attr->rq_psn = qp->r_psn & rdi->dparms.psn_mask;
1793 	attr->sq_psn = qp->s_next_psn & rdi->dparms.psn_mask;
1794 	attr->dest_qp_num = qp->remote_qpn;
1795 	attr->qp_access_flags = qp->qp_access_flags;
1796 	attr->cap.max_send_wr = qp->s_size - 1 -
1797 		rdi->dparms.reserved_operations;
1798 	attr->cap.max_recv_wr = qp->ibqp.srq ? 0 : qp->r_rq.size - 1;
1799 	attr->cap.max_send_sge = qp->s_max_sge;
1800 	attr->cap.max_recv_sge = qp->r_rq.max_sge;
1801 	attr->cap.max_inline_data = 0;
1802 	attr->ah_attr = qp->remote_ah_attr;
1803 	attr->alt_ah_attr = qp->alt_ah_attr;
1804 	attr->pkey_index = qp->s_pkey_index;
1805 	attr->alt_pkey_index = qp->s_alt_pkey_index;
1806 	attr->en_sqd_async_notify = 0;
1807 	attr->sq_draining = qp->s_draining;
1808 	attr->max_rd_atomic = qp->s_max_rd_atomic;
1809 	attr->max_dest_rd_atomic = qp->r_max_rd_atomic;
1810 	attr->min_rnr_timer = qp->r_min_rnr_timer;
1811 	attr->port_num = qp->port_num;
1812 	attr->timeout = qp->timeout;
1813 	attr->retry_cnt = qp->s_retry_cnt;
1814 	attr->rnr_retry = qp->s_rnr_retry_cnt;
1815 	attr->alt_port_num =
1816 		rdma_ah_get_port_num(&qp->alt_ah_attr);
1817 	attr->alt_timeout = qp->alt_timeout;
1818 
1819 	init_attr->event_handler = qp->ibqp.event_handler;
1820 	init_attr->qp_context = qp->ibqp.qp_context;
1821 	init_attr->send_cq = qp->ibqp.send_cq;
1822 	init_attr->recv_cq = qp->ibqp.recv_cq;
1823 	init_attr->srq = qp->ibqp.srq;
1824 	init_attr->cap = attr->cap;
1825 	if (qp->s_flags & RVT_S_SIGNAL_REQ_WR)
1826 		init_attr->sq_sig_type = IB_SIGNAL_REQ_WR;
1827 	else
1828 		init_attr->sq_sig_type = IB_SIGNAL_ALL_WR;
1829 	init_attr->qp_type = qp->ibqp.qp_type;
1830 	init_attr->port_num = qp->port_num;
1831 	return 0;
1832 }
1833 
1834 /**
1835  * rvt_post_recv - post a receive on a QP
1836  * @ibqp: the QP to post the receive on
1837  * @wr: the WR to post
1838  * @bad_wr: the first bad WR is put here
1839  *
1840  * This may be called from interrupt context.
1841  *
1842  * Return: 0 on success otherwise errno
1843  */
1844 int rvt_post_recv(struct ib_qp *ibqp, const struct ib_recv_wr *wr,
1845 		  const struct ib_recv_wr **bad_wr)
1846 {
1847 	struct rvt_qp *qp = ibqp_to_rvtqp(ibqp);
1848 	struct rvt_krwq *wq = qp->r_rq.kwq;
1849 	unsigned long flags;
1850 	int qp_err_flush = (ib_rvt_state_ops[qp->state] & RVT_FLUSH_RECV) &&
1851 				!qp->ibqp.srq;
1852 
1853 	/* Check that state is OK to post receive. */
1854 	if (!(ib_rvt_state_ops[qp->state] & RVT_POST_RECV_OK) || !wq) {
1855 		*bad_wr = wr;
1856 		return -EINVAL;
1857 	}
1858 
1859 	for (; wr; wr = wr->next) {
1860 		struct rvt_rwqe *wqe;
1861 		u32 next;
1862 		int i;
1863 
1864 		if ((unsigned)wr->num_sge > qp->r_rq.max_sge) {
1865 			*bad_wr = wr;
1866 			return -EINVAL;
1867 		}
1868 
1869 		spin_lock_irqsave(&qp->r_rq.kwq->p_lock, flags);
1870 		next = wq->head + 1;
1871 		if (next >= qp->r_rq.size)
1872 			next = 0;
1873 		if (next == READ_ONCE(wq->tail)) {
1874 			spin_unlock_irqrestore(&qp->r_rq.kwq->p_lock, flags);
1875 			*bad_wr = wr;
1876 			return -ENOMEM;
1877 		}
1878 		if (unlikely(qp_err_flush)) {
1879 			struct ib_wc wc;
1880 
1881 			memset(&wc, 0, sizeof(wc));
1882 			wc.qp = &qp->ibqp;
1883 			wc.opcode = IB_WC_RECV;
1884 			wc.wr_id = wr->wr_id;
1885 			wc.status = IB_WC_WR_FLUSH_ERR;
1886 			rvt_cq_enter(ibcq_to_rvtcq(qp->ibqp.recv_cq), &wc, 1);
1887 		} else {
1888 			wqe = rvt_get_rwqe_ptr(&qp->r_rq, wq->head);
1889 			wqe->wr_id = wr->wr_id;
1890 			wqe->num_sge = wr->num_sge;
1891 			for (i = 0; i < wr->num_sge; i++) {
1892 				wqe->sg_list[i].addr = wr->sg_list[i].addr;
1893 				wqe->sg_list[i].length = wr->sg_list[i].length;
1894 				wqe->sg_list[i].lkey = wr->sg_list[i].lkey;
1895 			}
1896 			/*
1897 			 * Make sure queue entry is written
1898 			 * before the head index.
1899 			 */
1900 			smp_store_release(&wq->head, next);
1901 		}
1902 		spin_unlock_irqrestore(&qp->r_rq.kwq->p_lock, flags);
1903 	}
1904 	return 0;
1905 }
1906 
1907 /**
1908  * rvt_qp_valid_operation - validate post send wr request
1909  * @qp: the qp
1910  * @post_parms_ the post send table for the driver
1911  * @wr: the work request
1912  *
1913  * The routine validates the operation based on the
1914  * validation table an returns the length of the operation
1915  * which can extend beyond the ib_send_bw.  Operation
1916  * dependent flags key atomic operation validation.
1917  *
1918  * There is an exception for UD qps that validates the pd and
1919  * overrides the length to include the additional UD specific
1920  * length.
1921  *
1922  * Returns a negative error or the length of the work request
1923  * for building the swqe.
1924  */
1925 static inline int rvt_qp_valid_operation(
1926 	struct rvt_qp *qp,
1927 	const struct rvt_operation_params *post_parms,
1928 	const struct ib_send_wr *wr)
1929 {
1930 	int len;
1931 
1932 	if (wr->opcode >= RVT_OPERATION_MAX || !post_parms[wr->opcode].length)
1933 		return -EINVAL;
1934 	if (!(post_parms[wr->opcode].qpt_support & BIT(qp->ibqp.qp_type)))
1935 		return -EINVAL;
1936 	if ((post_parms[wr->opcode].flags & RVT_OPERATION_PRIV) &&
1937 	    ibpd_to_rvtpd(qp->ibqp.pd)->user)
1938 		return -EINVAL;
1939 	if (post_parms[wr->opcode].flags & RVT_OPERATION_ATOMIC_SGE &&
1940 	    (wr->num_sge == 0 ||
1941 	     wr->sg_list[0].length < sizeof(u64) ||
1942 	     wr->sg_list[0].addr & (sizeof(u64) - 1)))
1943 		return -EINVAL;
1944 	if (post_parms[wr->opcode].flags & RVT_OPERATION_ATOMIC &&
1945 	    !qp->s_max_rd_atomic)
1946 		return -EINVAL;
1947 	len = post_parms[wr->opcode].length;
1948 	/* UD specific */
1949 	if (qp->ibqp.qp_type != IB_QPT_UC &&
1950 	    qp->ibqp.qp_type != IB_QPT_RC) {
1951 		if (qp->ibqp.pd != ud_wr(wr)->ah->pd)
1952 			return -EINVAL;
1953 		len = sizeof(struct ib_ud_wr);
1954 	}
1955 	return len;
1956 }
1957 
1958 /**
1959  * rvt_qp_is_avail - determine queue capacity
1960  * @qp: the qp
1961  * @rdi: the rdmavt device
1962  * @reserved_op: is reserved operation
1963  *
1964  * This assumes the s_hlock is held but the s_last
1965  * qp variable is uncontrolled.
1966  *
1967  * For non reserved operations, the qp->s_avail
1968  * may be changed.
1969  *
1970  * The return value is zero or a -ENOMEM.
1971  */
1972 static inline int rvt_qp_is_avail(
1973 	struct rvt_qp *qp,
1974 	struct rvt_dev_info *rdi,
1975 	bool reserved_op)
1976 {
1977 	u32 slast;
1978 	u32 avail;
1979 	u32 reserved_used;
1980 
1981 	/* see rvt_qp_wqe_unreserve() */
1982 	smp_mb__before_atomic();
1983 	if (unlikely(reserved_op)) {
1984 		/* see rvt_qp_wqe_unreserve() */
1985 		reserved_used = atomic_read(&qp->s_reserved_used);
1986 		if (reserved_used >= rdi->dparms.reserved_operations)
1987 			return -ENOMEM;
1988 		return 0;
1989 	}
1990 	/* non-reserved operations */
1991 	if (likely(qp->s_avail))
1992 		return 0;
1993 	/* See rvt_qp_complete_swqe() */
1994 	slast = smp_load_acquire(&qp->s_last);
1995 	if (qp->s_head >= slast)
1996 		avail = qp->s_size - (qp->s_head - slast);
1997 	else
1998 		avail = slast - qp->s_head;
1999 
2000 	reserved_used = atomic_read(&qp->s_reserved_used);
2001 	avail =  avail - 1 -
2002 		(rdi->dparms.reserved_operations - reserved_used);
2003 	/* insure we don't assign a negative s_avail */
2004 	if ((s32)avail <= 0)
2005 		return -ENOMEM;
2006 	qp->s_avail = avail;
2007 	if (WARN_ON(qp->s_avail >
2008 		    (qp->s_size - 1 - rdi->dparms.reserved_operations)))
2009 		rvt_pr_err(rdi,
2010 			   "More avail entries than QP RB size.\nQP: %u, size: %u, avail: %u\nhead: %u, tail: %u, cur: %u, acked: %u, last: %u",
2011 			   qp->ibqp.qp_num, qp->s_size, qp->s_avail,
2012 			   qp->s_head, qp->s_tail, qp->s_cur,
2013 			   qp->s_acked, qp->s_last);
2014 	return 0;
2015 }
2016 
2017 /**
2018  * rvt_post_one_wr - post one RC, UC, or UD send work request
2019  * @qp: the QP to post on
2020  * @wr: the work request to send
2021  * @call_send: kick the send engine into gear
2022  */
2023 static int rvt_post_one_wr(struct rvt_qp *qp,
2024 			   const struct ib_send_wr *wr,
2025 			   bool *call_send)
2026 {
2027 	struct rvt_swqe *wqe;
2028 	u32 next;
2029 	int i;
2030 	int j;
2031 	int acc;
2032 	struct rvt_lkey_table *rkt;
2033 	struct rvt_pd *pd;
2034 	struct rvt_dev_info *rdi = ib_to_rvt(qp->ibqp.device);
2035 	u8 log_pmtu;
2036 	int ret;
2037 	size_t cplen;
2038 	bool reserved_op;
2039 	int local_ops_delayed = 0;
2040 
2041 	BUILD_BUG_ON(IB_QPT_MAX >= (sizeof(u32) * BITS_PER_BYTE));
2042 
2043 	/* IB spec says that num_sge == 0 is OK. */
2044 	if (unlikely(wr->num_sge > qp->s_max_sge))
2045 		return -EINVAL;
2046 
2047 	ret = rvt_qp_valid_operation(qp, rdi->post_parms, wr);
2048 	if (ret < 0)
2049 		return ret;
2050 	cplen = ret;
2051 
2052 	/*
2053 	 * Local operations include fast register and local invalidate.
2054 	 * Fast register needs to be processed immediately because the
2055 	 * registered lkey may be used by following work requests and the
2056 	 * lkey needs to be valid at the time those requests are posted.
2057 	 * Local invalidate can be processed immediately if fencing is
2058 	 * not required and no previous local invalidate ops are pending.
2059 	 * Signaled local operations that have been processed immediately
2060 	 * need to have requests with "completion only" flags set posted
2061 	 * to the send queue in order to generate completions.
2062 	 */
2063 	if ((rdi->post_parms[wr->opcode].flags & RVT_OPERATION_LOCAL)) {
2064 		switch (wr->opcode) {
2065 		case IB_WR_REG_MR:
2066 			ret = rvt_fast_reg_mr(qp,
2067 					      reg_wr(wr)->mr,
2068 					      reg_wr(wr)->key,
2069 					      reg_wr(wr)->access);
2070 			if (ret || !(wr->send_flags & IB_SEND_SIGNALED))
2071 				return ret;
2072 			break;
2073 		case IB_WR_LOCAL_INV:
2074 			if ((wr->send_flags & IB_SEND_FENCE) ||
2075 			    atomic_read(&qp->local_ops_pending)) {
2076 				local_ops_delayed = 1;
2077 			} else {
2078 				ret = rvt_invalidate_rkey(
2079 					qp, wr->ex.invalidate_rkey);
2080 				if (ret || !(wr->send_flags & IB_SEND_SIGNALED))
2081 					return ret;
2082 			}
2083 			break;
2084 		default:
2085 			return -EINVAL;
2086 		}
2087 	}
2088 
2089 	reserved_op = rdi->post_parms[wr->opcode].flags &
2090 			RVT_OPERATION_USE_RESERVE;
2091 	/* check for avail */
2092 	ret = rvt_qp_is_avail(qp, rdi, reserved_op);
2093 	if (ret)
2094 		return ret;
2095 	next = qp->s_head + 1;
2096 	if (next >= qp->s_size)
2097 		next = 0;
2098 
2099 	rkt = &rdi->lkey_table;
2100 	pd = ibpd_to_rvtpd(qp->ibqp.pd);
2101 	wqe = rvt_get_swqe_ptr(qp, qp->s_head);
2102 
2103 	/* cplen has length from above */
2104 	memcpy(&wqe->wr, wr, cplen);
2105 
2106 	wqe->length = 0;
2107 	j = 0;
2108 	if (wr->num_sge) {
2109 		struct rvt_sge *last_sge = NULL;
2110 
2111 		acc = wr->opcode >= IB_WR_RDMA_READ ?
2112 			IB_ACCESS_LOCAL_WRITE : 0;
2113 		for (i = 0; i < wr->num_sge; i++) {
2114 			u32 length = wr->sg_list[i].length;
2115 
2116 			if (length == 0)
2117 				continue;
2118 			ret = rvt_lkey_ok(rkt, pd, &wqe->sg_list[j], last_sge,
2119 					  &wr->sg_list[i], acc);
2120 			if (unlikely(ret < 0))
2121 				goto bail_inval_free;
2122 			wqe->length += length;
2123 			if (ret)
2124 				last_sge = &wqe->sg_list[j];
2125 			j += ret;
2126 		}
2127 		wqe->wr.num_sge = j;
2128 	}
2129 
2130 	/*
2131 	 * Calculate and set SWQE PSN values prior to handing it off
2132 	 * to the driver's check routine. This give the driver the
2133 	 * opportunity to adjust PSN values based on internal checks.
2134 	 */
2135 	log_pmtu = qp->log_pmtu;
2136 	if (qp->allowed_ops == IB_OPCODE_UD) {
2137 		struct rvt_ah *ah = rvt_get_swqe_ah(wqe);
2138 
2139 		log_pmtu = ah->log_pmtu;
2140 		rdma_copy_ah_attr(wqe->ud_wr.attr, &ah->attr);
2141 	}
2142 
2143 	if (rdi->post_parms[wr->opcode].flags & RVT_OPERATION_LOCAL) {
2144 		if (local_ops_delayed)
2145 			atomic_inc(&qp->local_ops_pending);
2146 		else
2147 			wqe->wr.send_flags |= RVT_SEND_COMPLETION_ONLY;
2148 		wqe->ssn = 0;
2149 		wqe->psn = 0;
2150 		wqe->lpsn = 0;
2151 	} else {
2152 		wqe->ssn = qp->s_ssn++;
2153 		wqe->psn = qp->s_next_psn;
2154 		wqe->lpsn = wqe->psn +
2155 				(wqe->length ?
2156 					((wqe->length - 1) >> log_pmtu) :
2157 					0);
2158 	}
2159 
2160 	/* general part of wqe valid - allow for driver checks */
2161 	if (rdi->driver_f.setup_wqe) {
2162 		ret = rdi->driver_f.setup_wqe(qp, wqe, call_send);
2163 		if (ret < 0)
2164 			goto bail_inval_free_ref;
2165 	}
2166 
2167 	if (!(rdi->post_parms[wr->opcode].flags & RVT_OPERATION_LOCAL))
2168 		qp->s_next_psn = wqe->lpsn + 1;
2169 
2170 	if (unlikely(reserved_op)) {
2171 		wqe->wr.send_flags |= RVT_SEND_RESERVE_USED;
2172 		rvt_qp_wqe_reserve(qp, wqe);
2173 	} else {
2174 		wqe->wr.send_flags &= ~RVT_SEND_RESERVE_USED;
2175 		qp->s_avail--;
2176 	}
2177 	trace_rvt_post_one_wr(qp, wqe, wr->num_sge);
2178 	smp_wmb(); /* see request builders */
2179 	qp->s_head = next;
2180 
2181 	return 0;
2182 
2183 bail_inval_free_ref:
2184 	if (qp->allowed_ops == IB_OPCODE_UD)
2185 		rdma_destroy_ah_attr(wqe->ud_wr.attr);
2186 bail_inval_free:
2187 	/* release mr holds */
2188 	while (j) {
2189 		struct rvt_sge *sge = &wqe->sg_list[--j];
2190 
2191 		rvt_put_mr(sge->mr);
2192 	}
2193 	return ret;
2194 }
2195 
2196 /**
2197  * rvt_post_send - post a send on a QP
2198  * @ibqp: the QP to post the send on
2199  * @wr: the list of work requests to post
2200  * @bad_wr: the first bad WR is put here
2201  *
2202  * This may be called from interrupt context.
2203  *
2204  * Return: 0 on success else errno
2205  */
2206 int rvt_post_send(struct ib_qp *ibqp, const struct ib_send_wr *wr,
2207 		  const struct ib_send_wr **bad_wr)
2208 {
2209 	struct rvt_qp *qp = ibqp_to_rvtqp(ibqp);
2210 	struct rvt_dev_info *rdi = ib_to_rvt(ibqp->device);
2211 	unsigned long flags = 0;
2212 	bool call_send;
2213 	unsigned nreq = 0;
2214 	int err = 0;
2215 
2216 	spin_lock_irqsave(&qp->s_hlock, flags);
2217 
2218 	/*
2219 	 * Ensure QP state is such that we can send. If not bail out early,
2220 	 * there is no need to do this every time we post a send.
2221 	 */
2222 	if (unlikely(!(ib_rvt_state_ops[qp->state] & RVT_POST_SEND_OK))) {
2223 		spin_unlock_irqrestore(&qp->s_hlock, flags);
2224 		return -EINVAL;
2225 	}
2226 
2227 	/*
2228 	 * If the send queue is empty, and we only have a single WR then just go
2229 	 * ahead and kick the send engine into gear. Otherwise we will always
2230 	 * just schedule the send to happen later.
2231 	 */
2232 	call_send = qp->s_head == READ_ONCE(qp->s_last) && !wr->next;
2233 
2234 	for (; wr; wr = wr->next) {
2235 		err = rvt_post_one_wr(qp, wr, &call_send);
2236 		if (unlikely(err)) {
2237 			*bad_wr = wr;
2238 			goto bail;
2239 		}
2240 		nreq++;
2241 	}
2242 bail:
2243 	spin_unlock_irqrestore(&qp->s_hlock, flags);
2244 	if (nreq) {
2245 		/*
2246 		 * Only call do_send if there is exactly one packet, and the
2247 		 * driver said it was ok.
2248 		 */
2249 		if (nreq == 1 && call_send)
2250 			rdi->driver_f.do_send(qp);
2251 		else
2252 			rdi->driver_f.schedule_send_no_lock(qp);
2253 	}
2254 	return err;
2255 }
2256 
2257 /**
2258  * rvt_post_srq_recv - post a receive on a shared receive queue
2259  * @ibsrq: the SRQ to post the receive on
2260  * @wr: the list of work requests to post
2261  * @bad_wr: A pointer to the first WR to cause a problem is put here
2262  *
2263  * This may be called from interrupt context.
2264  *
2265  * Return: 0 on success else errno
2266  */
2267 int rvt_post_srq_recv(struct ib_srq *ibsrq, const struct ib_recv_wr *wr,
2268 		      const struct ib_recv_wr **bad_wr)
2269 {
2270 	struct rvt_srq *srq = ibsrq_to_rvtsrq(ibsrq);
2271 	struct rvt_krwq *wq;
2272 	unsigned long flags;
2273 
2274 	for (; wr; wr = wr->next) {
2275 		struct rvt_rwqe *wqe;
2276 		u32 next;
2277 		int i;
2278 
2279 		if ((unsigned)wr->num_sge > srq->rq.max_sge) {
2280 			*bad_wr = wr;
2281 			return -EINVAL;
2282 		}
2283 
2284 		spin_lock_irqsave(&srq->rq.kwq->p_lock, flags);
2285 		wq = srq->rq.kwq;
2286 		next = wq->head + 1;
2287 		if (next >= srq->rq.size)
2288 			next = 0;
2289 		if (next == READ_ONCE(wq->tail)) {
2290 			spin_unlock_irqrestore(&srq->rq.kwq->p_lock, flags);
2291 			*bad_wr = wr;
2292 			return -ENOMEM;
2293 		}
2294 
2295 		wqe = rvt_get_rwqe_ptr(&srq->rq, wq->head);
2296 		wqe->wr_id = wr->wr_id;
2297 		wqe->num_sge = wr->num_sge;
2298 		for (i = 0; i < wr->num_sge; i++) {
2299 			wqe->sg_list[i].addr = wr->sg_list[i].addr;
2300 			wqe->sg_list[i].length = wr->sg_list[i].length;
2301 			wqe->sg_list[i].lkey = wr->sg_list[i].lkey;
2302 		}
2303 		/* Make sure queue entry is written before the head index. */
2304 		smp_store_release(&wq->head, next);
2305 		spin_unlock_irqrestore(&srq->rq.kwq->p_lock, flags);
2306 	}
2307 	return 0;
2308 }
2309 
2310 /*
2311  * rvt used the internal kernel struct as part of its ABI, for now make sure
2312  * the kernel struct does not change layout. FIXME: rvt should never cast the
2313  * user struct to a kernel struct.
2314  */
2315 static struct ib_sge *rvt_cast_sge(struct rvt_wqe_sge *sge)
2316 {
2317 	BUILD_BUG_ON(offsetof(struct ib_sge, addr) !=
2318 		     offsetof(struct rvt_wqe_sge, addr));
2319 	BUILD_BUG_ON(offsetof(struct ib_sge, length) !=
2320 		     offsetof(struct rvt_wqe_sge, length));
2321 	BUILD_BUG_ON(offsetof(struct ib_sge, lkey) !=
2322 		     offsetof(struct rvt_wqe_sge, lkey));
2323 	return (struct ib_sge *)sge;
2324 }
2325 
2326 /*
2327  * Validate a RWQE and fill in the SGE state.
2328  * Return 1 if OK.
2329  */
2330 static int init_sge(struct rvt_qp *qp, struct rvt_rwqe *wqe)
2331 {
2332 	int i, j, ret;
2333 	struct ib_wc wc;
2334 	struct rvt_lkey_table *rkt;
2335 	struct rvt_pd *pd;
2336 	struct rvt_sge_state *ss;
2337 	struct rvt_dev_info *rdi = ib_to_rvt(qp->ibqp.device);
2338 
2339 	rkt = &rdi->lkey_table;
2340 	pd = ibpd_to_rvtpd(qp->ibqp.srq ? qp->ibqp.srq->pd : qp->ibqp.pd);
2341 	ss = &qp->r_sge;
2342 	ss->sg_list = qp->r_sg_list;
2343 	qp->r_len = 0;
2344 	for (i = j = 0; i < wqe->num_sge; i++) {
2345 		if (wqe->sg_list[i].length == 0)
2346 			continue;
2347 		/* Check LKEY */
2348 		ret = rvt_lkey_ok(rkt, pd, j ? &ss->sg_list[j - 1] : &ss->sge,
2349 				  NULL, rvt_cast_sge(&wqe->sg_list[i]),
2350 				  IB_ACCESS_LOCAL_WRITE);
2351 		if (unlikely(ret <= 0))
2352 			goto bad_lkey;
2353 		qp->r_len += wqe->sg_list[i].length;
2354 		j++;
2355 	}
2356 	ss->num_sge = j;
2357 	ss->total_len = qp->r_len;
2358 	return 1;
2359 
2360 bad_lkey:
2361 	while (j) {
2362 		struct rvt_sge *sge = --j ? &ss->sg_list[j - 1] : &ss->sge;
2363 
2364 		rvt_put_mr(sge->mr);
2365 	}
2366 	ss->num_sge = 0;
2367 	memset(&wc, 0, sizeof(wc));
2368 	wc.wr_id = wqe->wr_id;
2369 	wc.status = IB_WC_LOC_PROT_ERR;
2370 	wc.opcode = IB_WC_RECV;
2371 	wc.qp = &qp->ibqp;
2372 	/* Signal solicited completion event. */
2373 	rvt_cq_enter(ibcq_to_rvtcq(qp->ibqp.recv_cq), &wc, 1);
2374 	return 0;
2375 }
2376 
2377 /**
2378  * get_rvt_head - get head indices of the circular buffer
2379  * @rq: data structure for request queue entry
2380  * @ip: the QP
2381  *
2382  * Return - head index value
2383  */
2384 static inline u32 get_rvt_head(struct rvt_rq *rq, void *ip)
2385 {
2386 	u32 head;
2387 
2388 	if (ip)
2389 		head = RDMA_READ_UAPI_ATOMIC(rq->wq->head);
2390 	else
2391 		head = rq->kwq->head;
2392 
2393 	return head;
2394 }
2395 
2396 /**
2397  * rvt_get_rwqe - copy the next RWQE into the QP's RWQE
2398  * @qp: the QP
2399  * @wr_id_only: update qp->r_wr_id only, not qp->r_sge
2400  *
2401  * Return -1 if there is a local error, 0 if no RWQE is available,
2402  * otherwise return 1.
2403  *
2404  * Can be called from interrupt level.
2405  */
2406 int rvt_get_rwqe(struct rvt_qp *qp, bool wr_id_only)
2407 {
2408 	unsigned long flags;
2409 	struct rvt_rq *rq;
2410 	struct rvt_krwq *kwq = NULL;
2411 	struct rvt_rwq *wq;
2412 	struct rvt_srq *srq;
2413 	struct rvt_rwqe *wqe;
2414 	void (*handler)(struct ib_event *, void *);
2415 	u32 tail;
2416 	u32 head;
2417 	int ret;
2418 	void *ip = NULL;
2419 
2420 	if (qp->ibqp.srq) {
2421 		srq = ibsrq_to_rvtsrq(qp->ibqp.srq);
2422 		handler = srq->ibsrq.event_handler;
2423 		rq = &srq->rq;
2424 		ip = srq->ip;
2425 	} else {
2426 		srq = NULL;
2427 		handler = NULL;
2428 		rq = &qp->r_rq;
2429 		ip = qp->ip;
2430 	}
2431 
2432 	spin_lock_irqsave(&rq->kwq->c_lock, flags);
2433 	if (!(ib_rvt_state_ops[qp->state] & RVT_PROCESS_RECV_OK)) {
2434 		ret = 0;
2435 		goto unlock;
2436 	}
2437 	kwq = rq->kwq;
2438 	if (ip) {
2439 		wq = rq->wq;
2440 		tail = RDMA_READ_UAPI_ATOMIC(wq->tail);
2441 	} else {
2442 		tail = kwq->tail;
2443 	}
2444 
2445 	/* Validate tail before using it since it is user writable. */
2446 	if (tail >= rq->size)
2447 		tail = 0;
2448 
2449 	if (kwq->count < RVT_RWQ_COUNT_THRESHOLD) {
2450 		head = get_rvt_head(rq, ip);
2451 		kwq->count = rvt_get_rq_count(rq, head, tail);
2452 	}
2453 	if (unlikely(kwq->count == 0)) {
2454 		ret = 0;
2455 		goto unlock;
2456 	}
2457 	/* Make sure entry is read after the count is read. */
2458 	smp_rmb();
2459 	wqe = rvt_get_rwqe_ptr(rq, tail);
2460 	/*
2461 	 * Even though we update the tail index in memory, the verbs
2462 	 * consumer is not supposed to post more entries until a
2463 	 * completion is generated.
2464 	 */
2465 	if (++tail >= rq->size)
2466 		tail = 0;
2467 	if (ip)
2468 		RDMA_WRITE_UAPI_ATOMIC(wq->tail, tail);
2469 	else
2470 		kwq->tail = tail;
2471 	if (!wr_id_only && !init_sge(qp, wqe)) {
2472 		ret = -1;
2473 		goto unlock;
2474 	}
2475 	qp->r_wr_id = wqe->wr_id;
2476 
2477 	kwq->count--;
2478 	ret = 1;
2479 	set_bit(RVT_R_WRID_VALID, &qp->r_aflags);
2480 	if (handler) {
2481 		/*
2482 		 * Validate head pointer value and compute
2483 		 * the number of remaining WQEs.
2484 		 */
2485 		if (kwq->count < srq->limit) {
2486 			kwq->count =
2487 				rvt_get_rq_count(rq,
2488 						 get_rvt_head(rq, ip), tail);
2489 			if (kwq->count < srq->limit) {
2490 				struct ib_event ev;
2491 
2492 				srq->limit = 0;
2493 				spin_unlock_irqrestore(&rq->kwq->c_lock, flags);
2494 				ev.device = qp->ibqp.device;
2495 				ev.element.srq = qp->ibqp.srq;
2496 				ev.event = IB_EVENT_SRQ_LIMIT_REACHED;
2497 				handler(&ev, srq->ibsrq.srq_context);
2498 				goto bail;
2499 			}
2500 		}
2501 	}
2502 unlock:
2503 	spin_unlock_irqrestore(&rq->kwq->c_lock, flags);
2504 bail:
2505 	return ret;
2506 }
2507 EXPORT_SYMBOL(rvt_get_rwqe);
2508 
2509 /**
2510  * rvt_comm_est - handle trap with QP established
2511  * @qp: the QP
2512  */
2513 void rvt_comm_est(struct rvt_qp *qp)
2514 {
2515 	qp->r_flags |= RVT_R_COMM_EST;
2516 	if (qp->ibqp.event_handler) {
2517 		struct ib_event ev;
2518 
2519 		ev.device = qp->ibqp.device;
2520 		ev.element.qp = &qp->ibqp;
2521 		ev.event = IB_EVENT_COMM_EST;
2522 		qp->ibqp.event_handler(&ev, qp->ibqp.qp_context);
2523 	}
2524 }
2525 EXPORT_SYMBOL(rvt_comm_est);
2526 
2527 void rvt_rc_error(struct rvt_qp *qp, enum ib_wc_status err)
2528 {
2529 	unsigned long flags;
2530 	int lastwqe;
2531 
2532 	spin_lock_irqsave(&qp->s_lock, flags);
2533 	lastwqe = rvt_error_qp(qp, err);
2534 	spin_unlock_irqrestore(&qp->s_lock, flags);
2535 
2536 	if (lastwqe) {
2537 		struct ib_event ev;
2538 
2539 		ev.device = qp->ibqp.device;
2540 		ev.element.qp = &qp->ibqp;
2541 		ev.event = IB_EVENT_QP_LAST_WQE_REACHED;
2542 		qp->ibqp.event_handler(&ev, qp->ibqp.qp_context);
2543 	}
2544 }
2545 EXPORT_SYMBOL(rvt_rc_error);
2546 
2547 /*
2548  *  rvt_rnr_tbl_to_usec - return index into ib_rvt_rnr_table
2549  *  @index - the index
2550  *  return usec from an index into ib_rvt_rnr_table
2551  */
2552 unsigned long rvt_rnr_tbl_to_usec(u32 index)
2553 {
2554 	return ib_rvt_rnr_table[(index & IB_AETH_CREDIT_MASK)];
2555 }
2556 EXPORT_SYMBOL(rvt_rnr_tbl_to_usec);
2557 
2558 static inline unsigned long rvt_aeth_to_usec(u32 aeth)
2559 {
2560 	return ib_rvt_rnr_table[(aeth >> IB_AETH_CREDIT_SHIFT) &
2561 				  IB_AETH_CREDIT_MASK];
2562 }
2563 
2564 /*
2565  *  rvt_add_retry_timer_ext - add/start a retry timer
2566  *  @qp - the QP
2567  *  @shift - timeout shift to wait for multiple packets
2568  *  add a retry timer on the QP
2569  */
2570 void rvt_add_retry_timer_ext(struct rvt_qp *qp, u8 shift)
2571 {
2572 	struct ib_qp *ibqp = &qp->ibqp;
2573 	struct rvt_dev_info *rdi = ib_to_rvt(ibqp->device);
2574 
2575 	lockdep_assert_held(&qp->s_lock);
2576 	qp->s_flags |= RVT_S_TIMER;
2577        /* 4.096 usec. * (1 << qp->timeout) */
2578 	qp->s_timer.expires = jiffies + rdi->busy_jiffies +
2579 			      (qp->timeout_jiffies << shift);
2580 	add_timer(&qp->s_timer);
2581 }
2582 EXPORT_SYMBOL(rvt_add_retry_timer_ext);
2583 
2584 /**
2585  * rvt_add_rnr_timer - add/start an rnr timer on the QP
2586  * @qp: the QP
2587  * @aeth: aeth of RNR timeout, simulated aeth for loopback
2588  */
2589 void rvt_add_rnr_timer(struct rvt_qp *qp, u32 aeth)
2590 {
2591 	u32 to;
2592 
2593 	lockdep_assert_held(&qp->s_lock);
2594 	qp->s_flags |= RVT_S_WAIT_RNR;
2595 	to = rvt_aeth_to_usec(aeth);
2596 	trace_rvt_rnrnak_add(qp, to);
2597 	hrtimer_start(&qp->s_rnr_timer,
2598 		      ns_to_ktime(1000 * to), HRTIMER_MODE_REL_PINNED);
2599 }
2600 EXPORT_SYMBOL(rvt_add_rnr_timer);
2601 
2602 /**
2603  * rvt_stop_rc_timers - stop all timers
2604  * @qp: the QP
2605  * stop any pending timers
2606  */
2607 void rvt_stop_rc_timers(struct rvt_qp *qp)
2608 {
2609 	lockdep_assert_held(&qp->s_lock);
2610 	/* Remove QP from all timers */
2611 	if (qp->s_flags & (RVT_S_TIMER | RVT_S_WAIT_RNR)) {
2612 		qp->s_flags &= ~(RVT_S_TIMER | RVT_S_WAIT_RNR);
2613 		del_timer(&qp->s_timer);
2614 		hrtimer_try_to_cancel(&qp->s_rnr_timer);
2615 	}
2616 }
2617 EXPORT_SYMBOL(rvt_stop_rc_timers);
2618 
2619 /**
2620  * rvt_stop_rnr_timer - stop an rnr timer
2621  * @qp: the QP
2622  *
2623  * stop an rnr timer and return if the timer
2624  * had been pending.
2625  */
2626 static void rvt_stop_rnr_timer(struct rvt_qp *qp)
2627 {
2628 	lockdep_assert_held(&qp->s_lock);
2629 	/* Remove QP from rnr timer */
2630 	if (qp->s_flags & RVT_S_WAIT_RNR) {
2631 		qp->s_flags &= ~RVT_S_WAIT_RNR;
2632 		trace_rvt_rnrnak_stop(qp, 0);
2633 	}
2634 }
2635 
2636 /**
2637  * rvt_del_timers_sync - wait for any timeout routines to exit
2638  * @qp: the QP
2639  */
2640 void rvt_del_timers_sync(struct rvt_qp *qp)
2641 {
2642 	del_timer_sync(&qp->s_timer);
2643 	hrtimer_cancel(&qp->s_rnr_timer);
2644 }
2645 EXPORT_SYMBOL(rvt_del_timers_sync);
2646 
2647 /*
2648  * This is called from s_timer for missing responses.
2649  */
2650 static void rvt_rc_timeout(struct timer_list *t)
2651 {
2652 	struct rvt_qp *qp = from_timer(qp, t, s_timer);
2653 	struct rvt_dev_info *rdi = ib_to_rvt(qp->ibqp.device);
2654 	unsigned long flags;
2655 
2656 	spin_lock_irqsave(&qp->r_lock, flags);
2657 	spin_lock(&qp->s_lock);
2658 	if (qp->s_flags & RVT_S_TIMER) {
2659 		struct rvt_ibport *rvp = rdi->ports[qp->port_num - 1];
2660 
2661 		qp->s_flags &= ~RVT_S_TIMER;
2662 		rvp->n_rc_timeouts++;
2663 		del_timer(&qp->s_timer);
2664 		trace_rvt_rc_timeout(qp, qp->s_last_psn + 1);
2665 		if (rdi->driver_f.notify_restart_rc)
2666 			rdi->driver_f.notify_restart_rc(qp,
2667 							qp->s_last_psn + 1,
2668 							1);
2669 		rdi->driver_f.schedule_send(qp);
2670 	}
2671 	spin_unlock(&qp->s_lock);
2672 	spin_unlock_irqrestore(&qp->r_lock, flags);
2673 }
2674 
2675 /*
2676  * This is called from s_timer for RNR timeouts.
2677  */
2678 enum hrtimer_restart rvt_rc_rnr_retry(struct hrtimer *t)
2679 {
2680 	struct rvt_qp *qp = container_of(t, struct rvt_qp, s_rnr_timer);
2681 	struct rvt_dev_info *rdi = ib_to_rvt(qp->ibqp.device);
2682 	unsigned long flags;
2683 
2684 	spin_lock_irqsave(&qp->s_lock, flags);
2685 	rvt_stop_rnr_timer(qp);
2686 	trace_rvt_rnrnak_timeout(qp, 0);
2687 	rdi->driver_f.schedule_send(qp);
2688 	spin_unlock_irqrestore(&qp->s_lock, flags);
2689 	return HRTIMER_NORESTART;
2690 }
2691 EXPORT_SYMBOL(rvt_rc_rnr_retry);
2692 
2693 /**
2694  * rvt_qp_iter_init - initial for QP iteration
2695  * @rdi: rvt devinfo
2696  * @v: u64 value
2697  * @cb: user-defined callback
2698  *
2699  * This returns an iterator suitable for iterating QPs
2700  * in the system.
2701  *
2702  * The @cb is a user-defined callback and @v is a 64-bit
2703  * value passed to and relevant for processing in the
2704  * @cb.  An example use case would be to alter QP processing
2705  * based on criteria not part of the rvt_qp.
2706  *
2707  * Use cases that require memory allocation to succeed
2708  * must preallocate appropriately.
2709  *
2710  * Return: a pointer to an rvt_qp_iter or NULL
2711  */
2712 struct rvt_qp_iter *rvt_qp_iter_init(struct rvt_dev_info *rdi,
2713 				     u64 v,
2714 				     void (*cb)(struct rvt_qp *qp, u64 v))
2715 {
2716 	struct rvt_qp_iter *i;
2717 
2718 	i = kzalloc(sizeof(*i), GFP_KERNEL);
2719 	if (!i)
2720 		return NULL;
2721 
2722 	i->rdi = rdi;
2723 	/* number of special QPs (SMI/GSI) for device */
2724 	i->specials = rdi->ibdev.phys_port_cnt * 2;
2725 	i->v = v;
2726 	i->cb = cb;
2727 
2728 	return i;
2729 }
2730 EXPORT_SYMBOL(rvt_qp_iter_init);
2731 
2732 /**
2733  * rvt_qp_iter_next - return the next QP in iter
2734  * @iter: the iterator
2735  *
2736  * Fine grained QP iterator suitable for use
2737  * with debugfs seq_file mechanisms.
2738  *
2739  * Updates iter->qp with the current QP when the return
2740  * value is 0.
2741  *
2742  * Return: 0 - iter->qp is valid 1 - no more QPs
2743  */
2744 int rvt_qp_iter_next(struct rvt_qp_iter *iter)
2745 	__must_hold(RCU)
2746 {
2747 	int n = iter->n;
2748 	int ret = 1;
2749 	struct rvt_qp *pqp = iter->qp;
2750 	struct rvt_qp *qp;
2751 	struct rvt_dev_info *rdi = iter->rdi;
2752 
2753 	/*
2754 	 * The approach is to consider the special qps
2755 	 * as additional table entries before the
2756 	 * real hash table.  Since the qp code sets
2757 	 * the qp->next hash link to NULL, this works just fine.
2758 	 *
2759 	 * iter->specials is 2 * # ports
2760 	 *
2761 	 * n = 0..iter->specials is the special qp indices
2762 	 *
2763 	 * n = iter->specials..rdi->qp_dev->qp_table_size+iter->specials are
2764 	 * the potential hash bucket entries
2765 	 *
2766 	 */
2767 	for (; n <  rdi->qp_dev->qp_table_size + iter->specials; n++) {
2768 		if (pqp) {
2769 			qp = rcu_dereference(pqp->next);
2770 		} else {
2771 			if (n < iter->specials) {
2772 				struct rvt_ibport *rvp;
2773 				int pidx;
2774 
2775 				pidx = n % rdi->ibdev.phys_port_cnt;
2776 				rvp = rdi->ports[pidx];
2777 				qp = rcu_dereference(rvp->qp[n & 1]);
2778 			} else {
2779 				qp = rcu_dereference(
2780 					rdi->qp_dev->qp_table[
2781 						(n - iter->specials)]);
2782 			}
2783 		}
2784 		pqp = qp;
2785 		if (qp) {
2786 			iter->qp = qp;
2787 			iter->n = n;
2788 			return 0;
2789 		}
2790 	}
2791 	return ret;
2792 }
2793 EXPORT_SYMBOL(rvt_qp_iter_next);
2794 
2795 /**
2796  * rvt_qp_iter - iterate all QPs
2797  * @rdi: rvt devinfo
2798  * @v: a 64-bit value
2799  * @cb: a callback
2800  *
2801  * This provides a way for iterating all QPs.
2802  *
2803  * The @cb is a user-defined callback and @v is a 64-bit
2804  * value passed to and relevant for processing in the
2805  * cb.  An example use case would be to alter QP processing
2806  * based on criteria not part of the rvt_qp.
2807  *
2808  * The code has an internal iterator to simplify
2809  * non seq_file use cases.
2810  */
2811 void rvt_qp_iter(struct rvt_dev_info *rdi,
2812 		 u64 v,
2813 		 void (*cb)(struct rvt_qp *qp, u64 v))
2814 {
2815 	int ret;
2816 	struct rvt_qp_iter i = {
2817 		.rdi = rdi,
2818 		.specials = rdi->ibdev.phys_port_cnt * 2,
2819 		.v = v,
2820 		.cb = cb
2821 	};
2822 
2823 	rcu_read_lock();
2824 	do {
2825 		ret = rvt_qp_iter_next(&i);
2826 		if (!ret) {
2827 			rvt_get_qp(i.qp);
2828 			rcu_read_unlock();
2829 			i.cb(i.qp, i.v);
2830 			rcu_read_lock();
2831 			rvt_put_qp(i.qp);
2832 		}
2833 	} while (!ret);
2834 	rcu_read_unlock();
2835 }
2836 EXPORT_SYMBOL(rvt_qp_iter);
2837 
2838 /*
2839  * This should be called with s_lock held.
2840  */
2841 void rvt_send_complete(struct rvt_qp *qp, struct rvt_swqe *wqe,
2842 		       enum ib_wc_status status)
2843 {
2844 	u32 old_last, last;
2845 	struct rvt_dev_info *rdi;
2846 
2847 	if (!(ib_rvt_state_ops[qp->state] & RVT_PROCESS_OR_FLUSH_SEND))
2848 		return;
2849 	rdi = ib_to_rvt(qp->ibqp.device);
2850 
2851 	old_last = qp->s_last;
2852 	trace_rvt_qp_send_completion(qp, wqe, old_last);
2853 	last = rvt_qp_complete_swqe(qp, wqe, rdi->wc_opcode[wqe->wr.opcode],
2854 				    status);
2855 	if (qp->s_acked == old_last)
2856 		qp->s_acked = last;
2857 	if (qp->s_cur == old_last)
2858 		qp->s_cur = last;
2859 	if (qp->s_tail == old_last)
2860 		qp->s_tail = last;
2861 	if (qp->state == IB_QPS_SQD && last == qp->s_cur)
2862 		qp->s_draining = 0;
2863 }
2864 EXPORT_SYMBOL(rvt_send_complete);
2865 
2866 /**
2867  * rvt_copy_sge - copy data to SGE memory
2868  * @qp: associated QP
2869  * @ss: the SGE state
2870  * @data: the data to copy
2871  * @length: the length of the data
2872  * @release: boolean to release MR
2873  * @copy_last: do a separate copy of the last 8 bytes
2874  */
2875 void rvt_copy_sge(struct rvt_qp *qp, struct rvt_sge_state *ss,
2876 		  void *data, u32 length,
2877 		  bool release, bool copy_last)
2878 {
2879 	struct rvt_sge *sge = &ss->sge;
2880 	int i;
2881 	bool in_last = false;
2882 	bool cacheless_copy = false;
2883 	struct rvt_dev_info *rdi = ib_to_rvt(qp->ibqp.device);
2884 	struct rvt_wss *wss = rdi->wss;
2885 	unsigned int sge_copy_mode = rdi->dparms.sge_copy_mode;
2886 
2887 	if (sge_copy_mode == RVT_SGE_COPY_CACHELESS) {
2888 		cacheless_copy = length >= PAGE_SIZE;
2889 	} else if (sge_copy_mode == RVT_SGE_COPY_ADAPTIVE) {
2890 		if (length >= PAGE_SIZE) {
2891 			/*
2892 			 * NOTE: this *assumes*:
2893 			 * o The first vaddr is the dest.
2894 			 * o If multiple pages, then vaddr is sequential.
2895 			 */
2896 			wss_insert(wss, sge->vaddr);
2897 			if (length >= (2 * PAGE_SIZE))
2898 				wss_insert(wss, (sge->vaddr + PAGE_SIZE));
2899 
2900 			cacheless_copy = wss_exceeds_threshold(wss);
2901 		} else {
2902 			wss_advance_clean_counter(wss);
2903 		}
2904 	}
2905 
2906 	if (copy_last) {
2907 		if (length > 8) {
2908 			length -= 8;
2909 		} else {
2910 			copy_last = false;
2911 			in_last = true;
2912 		}
2913 	}
2914 
2915 again:
2916 	while (length) {
2917 		u32 len = rvt_get_sge_length(sge, length);
2918 
2919 		WARN_ON_ONCE(len == 0);
2920 		if (unlikely(in_last)) {
2921 			/* enforce byte transfer ordering */
2922 			for (i = 0; i < len; i++)
2923 				((u8 *)sge->vaddr)[i] = ((u8 *)data)[i];
2924 		} else if (cacheless_copy) {
2925 			cacheless_memcpy(sge->vaddr, data, len);
2926 		} else {
2927 			memcpy(sge->vaddr, data, len);
2928 		}
2929 		rvt_update_sge(ss, len, release);
2930 		data += len;
2931 		length -= len;
2932 	}
2933 
2934 	if (copy_last) {
2935 		copy_last = false;
2936 		in_last = true;
2937 		length = 8;
2938 		goto again;
2939 	}
2940 }
2941 EXPORT_SYMBOL(rvt_copy_sge);
2942 
2943 static enum ib_wc_status loopback_qp_drop(struct rvt_ibport *rvp,
2944 					  struct rvt_qp *sqp)
2945 {
2946 	rvp->n_pkt_drops++;
2947 	/*
2948 	 * For RC, the requester would timeout and retry so
2949 	 * shortcut the timeouts and just signal too many retries.
2950 	 */
2951 	return sqp->ibqp.qp_type == IB_QPT_RC ?
2952 		IB_WC_RETRY_EXC_ERR : IB_WC_SUCCESS;
2953 }
2954 
2955 /**
2956  * rvt_ruc_loopback - handle UC and RC loopback requests
2957  * @sqp: the sending QP
2958  *
2959  * This is called from rvt_do_send() to forward a WQE addressed to the same HFI
2960  * Note that although we are single threaded due to the send engine, we still
2961  * have to protect against post_send().  We don't have to worry about
2962  * receive interrupts since this is a connected protocol and all packets
2963  * will pass through here.
2964  */
2965 void rvt_ruc_loopback(struct rvt_qp *sqp)
2966 {
2967 	struct rvt_ibport *rvp =  NULL;
2968 	struct rvt_dev_info *rdi = ib_to_rvt(sqp->ibqp.device);
2969 	struct rvt_qp *qp;
2970 	struct rvt_swqe *wqe;
2971 	struct rvt_sge *sge;
2972 	unsigned long flags;
2973 	struct ib_wc wc;
2974 	u64 sdata;
2975 	atomic64_t *maddr;
2976 	enum ib_wc_status send_status;
2977 	bool release;
2978 	int ret;
2979 	bool copy_last = false;
2980 	int local_ops = 0;
2981 
2982 	rcu_read_lock();
2983 	rvp = rdi->ports[sqp->port_num - 1];
2984 
2985 	/*
2986 	 * Note that we check the responder QP state after
2987 	 * checking the requester's state.
2988 	 */
2989 
2990 	qp = rvt_lookup_qpn(ib_to_rvt(sqp->ibqp.device), rvp,
2991 			    sqp->remote_qpn);
2992 
2993 	spin_lock_irqsave(&sqp->s_lock, flags);
2994 
2995 	/* Return if we are already busy processing a work request. */
2996 	if ((sqp->s_flags & (RVT_S_BUSY | RVT_S_ANY_WAIT)) ||
2997 	    !(ib_rvt_state_ops[sqp->state] & RVT_PROCESS_OR_FLUSH_SEND))
2998 		goto unlock;
2999 
3000 	sqp->s_flags |= RVT_S_BUSY;
3001 
3002 again:
3003 	if (sqp->s_last == READ_ONCE(sqp->s_head))
3004 		goto clr_busy;
3005 	wqe = rvt_get_swqe_ptr(sqp, sqp->s_last);
3006 
3007 	/* Return if it is not OK to start a new work request. */
3008 	if (!(ib_rvt_state_ops[sqp->state] & RVT_PROCESS_NEXT_SEND_OK)) {
3009 		if (!(ib_rvt_state_ops[sqp->state] & RVT_FLUSH_SEND))
3010 			goto clr_busy;
3011 		/* We are in the error state, flush the work request. */
3012 		send_status = IB_WC_WR_FLUSH_ERR;
3013 		goto flush_send;
3014 	}
3015 
3016 	/*
3017 	 * We can rely on the entry not changing without the s_lock
3018 	 * being held until we update s_last.
3019 	 * We increment s_cur to indicate s_last is in progress.
3020 	 */
3021 	if (sqp->s_last == sqp->s_cur) {
3022 		if (++sqp->s_cur >= sqp->s_size)
3023 			sqp->s_cur = 0;
3024 	}
3025 	spin_unlock_irqrestore(&sqp->s_lock, flags);
3026 
3027 	if (!qp) {
3028 		send_status = loopback_qp_drop(rvp, sqp);
3029 		goto serr_no_r_lock;
3030 	}
3031 	spin_lock_irqsave(&qp->r_lock, flags);
3032 	if (!(ib_rvt_state_ops[qp->state] & RVT_PROCESS_RECV_OK) ||
3033 	    qp->ibqp.qp_type != sqp->ibqp.qp_type) {
3034 		send_status = loopback_qp_drop(rvp, sqp);
3035 		goto serr;
3036 	}
3037 
3038 	memset(&wc, 0, sizeof(wc));
3039 	send_status = IB_WC_SUCCESS;
3040 
3041 	release = true;
3042 	sqp->s_sge.sge = wqe->sg_list[0];
3043 	sqp->s_sge.sg_list = wqe->sg_list + 1;
3044 	sqp->s_sge.num_sge = wqe->wr.num_sge;
3045 	sqp->s_len = wqe->length;
3046 	switch (wqe->wr.opcode) {
3047 	case IB_WR_REG_MR:
3048 		goto send_comp;
3049 
3050 	case IB_WR_LOCAL_INV:
3051 		if (!(wqe->wr.send_flags & RVT_SEND_COMPLETION_ONLY)) {
3052 			if (rvt_invalidate_rkey(sqp,
3053 						wqe->wr.ex.invalidate_rkey))
3054 				send_status = IB_WC_LOC_PROT_ERR;
3055 			local_ops = 1;
3056 		}
3057 		goto send_comp;
3058 
3059 	case IB_WR_SEND_WITH_INV:
3060 	case IB_WR_SEND_WITH_IMM:
3061 	case IB_WR_SEND:
3062 		ret = rvt_get_rwqe(qp, false);
3063 		if (ret < 0)
3064 			goto op_err;
3065 		if (!ret)
3066 			goto rnr_nak;
3067 		if (wqe->length > qp->r_len)
3068 			goto inv_err;
3069 		switch (wqe->wr.opcode) {
3070 		case IB_WR_SEND_WITH_INV:
3071 			if (!rvt_invalidate_rkey(qp,
3072 						 wqe->wr.ex.invalidate_rkey)) {
3073 				wc.wc_flags = IB_WC_WITH_INVALIDATE;
3074 				wc.ex.invalidate_rkey =
3075 					wqe->wr.ex.invalidate_rkey;
3076 			}
3077 			break;
3078 		case IB_WR_SEND_WITH_IMM:
3079 			wc.wc_flags = IB_WC_WITH_IMM;
3080 			wc.ex.imm_data = wqe->wr.ex.imm_data;
3081 			break;
3082 		default:
3083 			break;
3084 		}
3085 		break;
3086 
3087 	case IB_WR_RDMA_WRITE_WITH_IMM:
3088 		if (unlikely(!(qp->qp_access_flags & IB_ACCESS_REMOTE_WRITE)))
3089 			goto inv_err;
3090 		wc.wc_flags = IB_WC_WITH_IMM;
3091 		wc.ex.imm_data = wqe->wr.ex.imm_data;
3092 		ret = rvt_get_rwqe(qp, true);
3093 		if (ret < 0)
3094 			goto op_err;
3095 		if (!ret)
3096 			goto rnr_nak;
3097 		/* skip copy_last set and qp_access_flags recheck */
3098 		goto do_write;
3099 	case IB_WR_RDMA_WRITE:
3100 		copy_last = rvt_is_user_qp(qp);
3101 		if (unlikely(!(qp->qp_access_flags & IB_ACCESS_REMOTE_WRITE)))
3102 			goto inv_err;
3103 do_write:
3104 		if (wqe->length == 0)
3105 			break;
3106 		if (unlikely(!rvt_rkey_ok(qp, &qp->r_sge.sge, wqe->length,
3107 					  wqe->rdma_wr.remote_addr,
3108 					  wqe->rdma_wr.rkey,
3109 					  IB_ACCESS_REMOTE_WRITE)))
3110 			goto acc_err;
3111 		qp->r_sge.sg_list = NULL;
3112 		qp->r_sge.num_sge = 1;
3113 		qp->r_sge.total_len = wqe->length;
3114 		break;
3115 
3116 	case IB_WR_RDMA_READ:
3117 		if (unlikely(!(qp->qp_access_flags & IB_ACCESS_REMOTE_READ)))
3118 			goto inv_err;
3119 		if (unlikely(!rvt_rkey_ok(qp, &sqp->s_sge.sge, wqe->length,
3120 					  wqe->rdma_wr.remote_addr,
3121 					  wqe->rdma_wr.rkey,
3122 					  IB_ACCESS_REMOTE_READ)))
3123 			goto acc_err;
3124 		release = false;
3125 		sqp->s_sge.sg_list = NULL;
3126 		sqp->s_sge.num_sge = 1;
3127 		qp->r_sge.sge = wqe->sg_list[0];
3128 		qp->r_sge.sg_list = wqe->sg_list + 1;
3129 		qp->r_sge.num_sge = wqe->wr.num_sge;
3130 		qp->r_sge.total_len = wqe->length;
3131 		break;
3132 
3133 	case IB_WR_ATOMIC_CMP_AND_SWP:
3134 	case IB_WR_ATOMIC_FETCH_AND_ADD:
3135 		if (unlikely(!(qp->qp_access_flags & IB_ACCESS_REMOTE_ATOMIC)))
3136 			goto inv_err;
3137 		if (unlikely(!rvt_rkey_ok(qp, &qp->r_sge.sge, sizeof(u64),
3138 					  wqe->atomic_wr.remote_addr,
3139 					  wqe->atomic_wr.rkey,
3140 					  IB_ACCESS_REMOTE_ATOMIC)))
3141 			goto acc_err;
3142 		/* Perform atomic OP and save result. */
3143 		maddr = (atomic64_t *)qp->r_sge.sge.vaddr;
3144 		sdata = wqe->atomic_wr.compare_add;
3145 		*(u64 *)sqp->s_sge.sge.vaddr =
3146 			(wqe->wr.opcode == IB_WR_ATOMIC_FETCH_AND_ADD) ?
3147 			(u64)atomic64_add_return(sdata, maddr) - sdata :
3148 			(u64)cmpxchg((u64 *)qp->r_sge.sge.vaddr,
3149 				      sdata, wqe->atomic_wr.swap);
3150 		rvt_put_mr(qp->r_sge.sge.mr);
3151 		qp->r_sge.num_sge = 0;
3152 		goto send_comp;
3153 
3154 	default:
3155 		send_status = IB_WC_LOC_QP_OP_ERR;
3156 		goto serr;
3157 	}
3158 
3159 	sge = &sqp->s_sge.sge;
3160 	while (sqp->s_len) {
3161 		u32 len = rvt_get_sge_length(sge, sqp->s_len);
3162 
3163 		WARN_ON_ONCE(len == 0);
3164 		rvt_copy_sge(qp, &qp->r_sge, sge->vaddr,
3165 			     len, release, copy_last);
3166 		rvt_update_sge(&sqp->s_sge, len, !release);
3167 		sqp->s_len -= len;
3168 	}
3169 	if (release)
3170 		rvt_put_ss(&qp->r_sge);
3171 
3172 	if (!test_and_clear_bit(RVT_R_WRID_VALID, &qp->r_aflags))
3173 		goto send_comp;
3174 
3175 	if (wqe->wr.opcode == IB_WR_RDMA_WRITE_WITH_IMM)
3176 		wc.opcode = IB_WC_RECV_RDMA_WITH_IMM;
3177 	else
3178 		wc.opcode = IB_WC_RECV;
3179 	wc.wr_id = qp->r_wr_id;
3180 	wc.status = IB_WC_SUCCESS;
3181 	wc.byte_len = wqe->length;
3182 	wc.qp = &qp->ibqp;
3183 	wc.src_qp = qp->remote_qpn;
3184 	wc.slid = rdma_ah_get_dlid(&qp->remote_ah_attr) & U16_MAX;
3185 	wc.sl = rdma_ah_get_sl(&qp->remote_ah_attr);
3186 	wc.port_num = 1;
3187 	/* Signal completion event if the solicited bit is set. */
3188 	rvt_recv_cq(qp, &wc, wqe->wr.send_flags & IB_SEND_SOLICITED);
3189 
3190 send_comp:
3191 	spin_unlock_irqrestore(&qp->r_lock, flags);
3192 	spin_lock_irqsave(&sqp->s_lock, flags);
3193 	rvp->n_loop_pkts++;
3194 flush_send:
3195 	sqp->s_rnr_retry = sqp->s_rnr_retry_cnt;
3196 	rvt_send_complete(sqp, wqe, send_status);
3197 	if (local_ops) {
3198 		atomic_dec(&sqp->local_ops_pending);
3199 		local_ops = 0;
3200 	}
3201 	goto again;
3202 
3203 rnr_nak:
3204 	/* Handle RNR NAK */
3205 	if (qp->ibqp.qp_type == IB_QPT_UC)
3206 		goto send_comp;
3207 	rvp->n_rnr_naks++;
3208 	/*
3209 	 * Note: we don't need the s_lock held since the BUSY flag
3210 	 * makes this single threaded.
3211 	 */
3212 	if (sqp->s_rnr_retry == 0) {
3213 		send_status = IB_WC_RNR_RETRY_EXC_ERR;
3214 		goto serr;
3215 	}
3216 	if (sqp->s_rnr_retry_cnt < 7)
3217 		sqp->s_rnr_retry--;
3218 	spin_unlock_irqrestore(&qp->r_lock, flags);
3219 	spin_lock_irqsave(&sqp->s_lock, flags);
3220 	if (!(ib_rvt_state_ops[sqp->state] & RVT_PROCESS_RECV_OK))
3221 		goto clr_busy;
3222 	rvt_add_rnr_timer(sqp, qp->r_min_rnr_timer <<
3223 				IB_AETH_CREDIT_SHIFT);
3224 	goto clr_busy;
3225 
3226 op_err:
3227 	send_status = IB_WC_REM_OP_ERR;
3228 	wc.status = IB_WC_LOC_QP_OP_ERR;
3229 	goto err;
3230 
3231 inv_err:
3232 	send_status =
3233 		sqp->ibqp.qp_type == IB_QPT_RC ?
3234 			IB_WC_REM_INV_REQ_ERR :
3235 			IB_WC_SUCCESS;
3236 	wc.status = IB_WC_LOC_QP_OP_ERR;
3237 	goto err;
3238 
3239 acc_err:
3240 	send_status = IB_WC_REM_ACCESS_ERR;
3241 	wc.status = IB_WC_LOC_PROT_ERR;
3242 err:
3243 	/* responder goes to error state */
3244 	rvt_rc_error(qp, wc.status);
3245 
3246 serr:
3247 	spin_unlock_irqrestore(&qp->r_lock, flags);
3248 serr_no_r_lock:
3249 	spin_lock_irqsave(&sqp->s_lock, flags);
3250 	rvt_send_complete(sqp, wqe, send_status);
3251 	if (sqp->ibqp.qp_type == IB_QPT_RC) {
3252 		int lastwqe = rvt_error_qp(sqp, IB_WC_WR_FLUSH_ERR);
3253 
3254 		sqp->s_flags &= ~RVT_S_BUSY;
3255 		spin_unlock_irqrestore(&sqp->s_lock, flags);
3256 		if (lastwqe) {
3257 			struct ib_event ev;
3258 
3259 			ev.device = sqp->ibqp.device;
3260 			ev.element.qp = &sqp->ibqp;
3261 			ev.event = IB_EVENT_QP_LAST_WQE_REACHED;
3262 			sqp->ibqp.event_handler(&ev, sqp->ibqp.qp_context);
3263 		}
3264 		goto done;
3265 	}
3266 clr_busy:
3267 	sqp->s_flags &= ~RVT_S_BUSY;
3268 unlock:
3269 	spin_unlock_irqrestore(&sqp->s_lock, flags);
3270 done:
3271 	rcu_read_unlock();
3272 }
3273 EXPORT_SYMBOL(rvt_ruc_loopback);
3274