Merge pull request #1859 from sue-miller/doorbell-fix

mlx5: Fix NULL pointer dereference in mlx5_free_db()
diff --git a/providers/irdma/uk.c b/providers/irdma/uk.c
index 571ccea..4556676 100644
--- a/providers/irdma/uk.c
+++ b/providers/irdma/uk.c
@@ -1257,6 +1257,17 @@
 }
 
 /**
+ * irdma_srq_release_wqe - release an SRQ WQE
+ * @srq: SRQ
+ */
+static void irdma_srq_release_wqe(struct irdma_srq_uk *srq)
+{
+	pthread_spin_lock(srq->lock);
+	IRDMA_RING_MOVE_TAIL(srq->srq_ring);
+	pthread_spin_unlock(srq->lock);
+}
+
+/**
  * irdma_uk_cq_poll_cmpl - get cq completion info
  * @cq: hw cq
  * @info: cq poll information returned
@@ -1355,6 +1366,10 @@
 		get_64bit_val(cqe, 40, (__u64 *)&qp);
 	else
 		qp = (struct irdma_qp_uk *)(uintptr_t)comp_ctx;
+	if (!qp || qp->destroy_pending) {
+		ret_code = EFAULT;
+		goto exit;
+	}
 	if (info->error) {
 		info->major_err = FIELD_GET(IRDMA_CQ_MAJERR, qword3);
 		info->minor_err = FIELD_GET(IRDMA_CQ_MINERR, qword3);
@@ -1401,10 +1416,6 @@
 	info->ud_src_qpn = (__u32)FIELD_GET(IRDMACQ_UDSRCQPN, qword2);
 	info->solicited_event = (bool)FIELD_GET(IRDMACQ_SOEVENT, qword3);
 
-	if (!qp || qp->destroy_pending) {
-		ret_code = EFAULT;
-		goto exit;
-	}
 	wqe_idx = (__u32)FIELD_GET(IRDMA_CQ_WQEIDX, qword3);
 	info->qp_handle = (irdma_qp_handle)(uintptr_t)qp;
 	info->op_type = (__u8)FIELD_GET(IRDMACQ_OP, qword3);
@@ -1421,7 +1432,8 @@
 		} else {
 			info->stag_invalid_set = false;
 		}
-		IRDMA_RING_MOVE_TAIL(srq->srq_ring);
+
+		irdma_srq_release_wqe(srq);
 		pring = &srq->srq_ring;
 	} else if (info->q_type == IRDMA_CQE_QTYPE_RQ && !is_srq) {
 		__u32 array_idx;
@@ -1873,10 +1885,10 @@
 
 /**
  * irdma_uk_clean_cq - clean cq entries
- * @q: completion context
+ * @qp: QP
  * @cq: cq to clean
  */
-void irdma_uk_clean_cq(void *q, struct irdma_cq_uk *cq)
+void irdma_uk_clean_cq(struct irdma_qp_uk *qp, struct irdma_cq_uk *cq)
 {
 	__le64 *cqe;
 	__u64 qword3, comp_ctx;
@@ -1899,9 +1911,19 @@
 		/* Ensure CQE contents are read after valid bit is checked */
 		udma_from_device_barrier();
 
-		get_64bit_val(cqe, 8, &comp_ctx);
-		if ((void *)(uintptr_t)comp_ctx == q)
-			set_64bit_val(cqe, 8, 0);
+		if (cq->avoid_mem_cflct && FIELD_GET(IRDMA_CQ_SRQ, qword3)) {
+			get_64bit_val(cqe, 40, &comp_ctx);
+			if ((struct irdma_qp_uk *)(uintptr_t)comp_ctx == qp) {
+				if (qp->srq_uk &&
+				    FIELD_GET(IRDMA_CQ_SQ, qword3) == IRDMA_CQE_QTYPE_RQ)
+					irdma_srq_release_wqe(qp->srq_uk);
+				set_64bit_val(cqe, 40, 0);
+			}
+		} else {
+			get_64bit_val(cqe, 8, &comp_ctx);
+			if ((struct irdma_qp_uk *)(uintptr_t)comp_ctx == qp)
+				set_64bit_val(cqe, 8, 0);
+		}
 
 		cq_head = (cq_head + 1) % cq->cq_ring.size;
 		if (!cq_head)
diff --git a/providers/irdma/user.h b/providers/irdma/user.h
index 9882907..6b4a991 100644
--- a/providers/irdma/user.h
+++ b/providers/irdma/user.h
@@ -471,6 +471,7 @@
 	__u8 wqe_size;
 	__u8 wqe_size_multiplier;
 	__u8 deferred_flag;
+	pthread_spinlock_t *lock;
 };
 
 struct irdma_srq_uk_init_info {
@@ -592,7 +593,7 @@
 				   struct irdma_post_sq_info *info);
 __le64 *irdma_srq_get_next_recv_wqe(struct irdma_srq_uk *srq, __u32 *wqe_idx);
 __le64 *irdma_qp_get_next_recv_wqe(struct irdma_qp_uk *qp, __u32 *wqe_idx);
-void irdma_uk_clean_cq(void *q, struct irdma_cq_uk *cq);
+void irdma_uk_clean_cq(struct irdma_qp_uk *qp, struct irdma_cq_uk *cq);
 int irdma_nop(struct irdma_qp_uk *qp, __u64 wr_id, bool signaled, bool post_sq);
 int irdma_fragcnt_to_quanta_sq(__u32 frag_cnt, __u16 *quanta);
 int irdma_fragcnt_to_wqesize_rq(__u32 frag_cnt, __u16 *wqe_size);
diff --git a/providers/irdma/uverbs.c b/providers/irdma/uverbs.c
index 55cf086..6dc88e2 100644
--- a/providers/irdma/uverbs.c
+++ b/providers/irdma/uverbs.c
@@ -462,6 +462,7 @@
 	info.srq_id = resp.srq_id;
 	info.srq_size = resp.srq_size;
 
+	iwusrq->srq.lock = &iwusrq->lock;
 	ret = irdma_uk_srq_init(&iwusrq->srq, &info);
 	if (ret)
 		goto err_srq_init;
diff --git a/pyverbs/cq.pyx b/pyverbs/cq.pyx
index 06dbe7f..2a696f2 100644
--- a/pyverbs/cq.pyx
+++ b/pyverbs/cq.pyx
@@ -14,6 +14,34 @@
 from pyverbs.wq cimport WQ
 
 
+cdef _poll_cq(v.ibv_cq *cq, num_entries):
+    """
+    Polls the given CQ for completions.
+    :param cq: The CQ to poll
+    :param num_entries: number of completions to pull
+    :return: (npolled, wcs): The number of polled completions and an array
+             of the polled completions
+    """
+    cdef v.ibv_wc wc
+    wcs = []
+    npolled = 0
+
+    while npolled < num_entries:
+        rc = v.ibv_poll_cq(cq, 1, &wc)
+        if rc < 0:
+            raise PyverbsRDMAError('Failed to poll CQ', -rc)
+        if rc == 0:
+            break
+        npolled += 1
+        wcs.append(WC(wr_id=wc.wr_id, status=wc.status, opcode=wc.opcode,
+                      vendor_err=wc.vendor_err, byte_len=wc.byte_len,
+                      qp_num=wc.qp_num, src_qp=wc.src_qp,
+                      imm_data=wc.imm_data, wc_flags=wc.wc_flags,
+                      pkey_index=wc.pkey_index, slid=wc.slid, sl=wc.sl,
+                      dlid_path_bits=wc.dlid_path_bits))
+    return npolled, wcs
+
+
 cdef class CompChannel(PyverbsCM):
     """
     A completion channel is a file descriptor used to deliver completion
@@ -157,24 +185,7 @@
         :return: (npolled, wcs): The number of polled completions and an array
                  of the polled completions
         """
-        cdef v.ibv_wc wc
-        wcs = []
-        npolled = 0
-
-        while npolled < num_entries:
-            rc = v.ibv_poll_cq(self.cq, 1, &wc)
-            if rc < 0:
-                raise PyverbsRDMAError('Failed to poll CQ', -rc)
-            if rc == 0:
-                break;
-            npolled += 1
-            wcs.append(WC(wr_id=wc.wr_id, status=wc.status, opcode=wc.opcode,
-                          vendor_err=wc.vendor_err, byte_len=wc.byte_len,
-                          qp_num=wc.qp_num, src_qp=wc.src_qp,
-                          imm_data=wc.imm_data, wc_flags=wc.wc_flags,
-                          pkey_index=wc.pkey_index, slid=wc.slid, sl=wc.sl,
-                          dlid_path_bits=wc.dlid_path_bits))
-        return npolled, wcs
+        return _poll_cq(self.cq, num_entries)
 
     def req_notify(self, solicited_only = False):
         """
@@ -363,6 +374,7 @@
             if rc != 0:
                 raise PyverbsRDMAError('Failed to destroy CQEX', rc)
             self.cq = NULL
+            self.ibv_cq = NULL
             self.context = None
 
     def start_poll(self, PollCqAttr attr):
@@ -389,6 +401,19 @@
         """
         return v.ibv_end_poll(self.cq)
 
+    def poll(self, num_entries=1):
+        """
+        Polls the extended CQ for completions through the legacy path,
+        returning regular WC objects. Useful when the provider supports an
+        extended CQ but not the extended polling API.
+        Must not be called between start_poll() and end_poll(), since the
+        provider may keep the CQ locked for the whole batch.
+        :param num_entries: number of completions to pull
+        :return: (npolled, wcs): The number of polled completions and an array
+                 of the polled completions
+        """
+        return _poll_cq(self.ibv_cq, num_entries)
+
     def read_opcode(self):
         return v.ibv_wc_read_opcode(self.cq)
     def read_vendor_err(self):
diff --git a/redhat/rdma-core.spec b/redhat/rdma-core.spec
index d69fcde..8046dfd 100644
--- a/redhat/rdma-core.spec
+++ b/redhat/rdma-core.spec
@@ -82,8 +82,9 @@
 %define cmake_install DESTDIR=%{buildroot} make install
 %endif
 
-%if 0%{?fedora} >= 25 || 0%{?rhel} == 8
-# pandoc was introduced in FC25, Centos8
+# pandoc was introduced in FC25, Centos8. Amazon Linux does not ship pandoc,
+# build there from release tarballs with pre-built man pages.
+%if (0%{?fedora} >= 25 || 0%{?rhel} == 8) && !0%{?amzn}
 BuildRequires: pandoc
 %endif
 
diff --git a/tests/test_mlx5_vfio.py b/tests/test_mlx5_vfio.py
index a223405..bec9d16 100644
--- a/tests/test_mlx5_vfio.py
+++ b/tests/test_mlx5_vfio.py
@@ -31,7 +31,7 @@
 class Mlx5VfioResources(Mlx5DevxRcResources):
     def __init__(self, ib_port, pci_name, gid_index=None, ctx=None, activate_port_state=False):
         self.pci_name = pci_name
-        self.ctx = ctx
+        self._provided_ctx = ctx
         super().__init__(None, ib_port, gid_index, activate_port_state=activate_port_state)
 
     def create_context(self):
@@ -42,7 +42,8 @@
         same context would be used.
         :return: None
         """
-        if self.ctx:
+        if self._provided_ctx:
+            self.ctx = self._provided_ctx
             return
         try:
             vfio_attr = Mlx5VfioAttr(pci_name=self.pci_name)
@@ -78,8 +79,9 @@
 
         ci = self.cons_index + cc
         entry = ci & (self.nent - 1)
-        eqe_bytes = mem.read64(self.eq.vaddr + entry * len(SwEqe()))
-        eqe_bytes = eqe_bytes.to_bytes(length=8, byteorder='little')
+        eqe_size = len(SwEqe())
+        offset = self.eq.vaddr + entry * eqe_size
+        eqe_bytes = mem.read(offset, eqe_size)
         eqe = SwEqe(eqe_bytes)
         if (eqe.owner & 1) ^ (not(not(ci & self.nent))):
             eqe = None
@@ -101,11 +103,11 @@
     def init_dveq_buff(self):
         from tests.mlx5_prm_structs import SwEqe
 
+        eqe_size = len(SwEqe())
         for i in range(self.nent):
-            eqe_bytes = mem.read64(self.eq.vaddr + i * len(SwEqe()))
-            eqe_bytes = eqe_bytes.to_bytes(length=8, byteorder='little')
-            eqe = SwEqe(eqe_bytes)
-            eqe.owner = 0x1
+            offset = self.eq.vaddr + i * eqe_size
+            eqe = SwEqe(owner=0x1)
+            mem.write(offset, bytes(eqe), eqe_size)
         self.update_ci(0)
 
     def update_cc(self, cc):