Merge 'origin/release-2019' into release-2020
[alexxy/gromacs.git] / src / gromacs / nbnxm / pairlist.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014,2015,2016,2017,2018,2019, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35
36 #include "gmxpre.h"
37
38 #include "pairlist.h"
39
40 #include "config.h"
41
42 #include <cassert>
43 #include <cmath>
44 #include <cstring>
45
46 #include <algorithm>
47
48 #include "gromacs/domdec/domdec_struct.h"
49 #include "gromacs/gmxlib/nrnb.h"
50 #include "gromacs/math/functions.h"
51 #include "gromacs/math/utilities.h"
52 #include "gromacs/math/vec.h"
53 #include "gromacs/mdlib/gmx_omp_nthreads.h"
54 #include "gromacs/mdtypes/group.h"
55 #include "gromacs/mdtypes/md_enums.h"
56 #include "gromacs/nbnxm/gpu_data_mgmt.h"
57 #include "gromacs/pbcutil/ishift.h"
58 #include "gromacs/pbcutil/pbc.h"
59 #include "gromacs/simd/simd.h"
60 #include "gromacs/simd/vector_operations.h"
61 #include "gromacs/topology/block.h"
62 #include "gromacs/utility/exceptions.h"
63 #include "gromacs/utility/fatalerror.h"
64 #include "gromacs/utility/gmxomp.h"
65 #include "gromacs/utility/smalloc.h"
66
67 #include "atomdata.h"
68 #include "boundingboxes.h"
69 #include "clusterdistancekerneltype.h"
70 #include "gridset.h"
71 #include "nbnxm_geometry.h"
72 #include "nbnxm_simd.h"
73 #include "pairlistset.h"
74 #include "pairlistsets.h"
75 #include "pairlistwork.h"
76 #include "pairsearch.h"
77
78 using namespace gmx; // TODO: Remove when this file is moved into gmx namespace
79
80 using BoundingBox   = Nbnxm::BoundingBox;   // TODO: Remove when refactoring this file
81 using BoundingBox1D = Nbnxm::BoundingBox1D; // TODO: Remove when refactoring this file
82
83 using Grid = Nbnxm::Grid; // TODO: Remove when refactoring this file
84
85 // Convience alias for partial Nbnxn namespace usage
86 using InteractionLocality = gmx::InteractionLocality;
87
88 /* We shift the i-particles backward for PBC.
89  * This leads to more conditionals than shifting forward.
90  * We do this to get more balanced pair lists.
91  */
92 constexpr bool c_pbcShiftBackward = true;
93
94 /* Layout for the nonbonded NxN pair lists */
95 enum class NbnxnLayout
96 {
97     NoSimd4x4, // i-cluster size 4, j-cluster size 4
98     Simd4xN,   // i-cluster size 4, j-cluster size SIMD width
99     Simd2xNN,  // i-cluster size 4, j-cluster size half SIMD width
100     Gpu8x8x8   // i-cluster size 8, j-cluster size 8 + super-clustering
101 };
102
103 #if GMX_SIMD
104 /* Returns the j-cluster size */
105 template<NbnxnLayout layout>
106 static constexpr int jClusterSize()
107 {
108     static_assert(layout == NbnxnLayout::NoSimd4x4 || layout == NbnxnLayout::Simd4xN
109                           || layout == NbnxnLayout::Simd2xNN,
110                   "Currently jClusterSize only supports CPU layouts");
111
112     return layout == NbnxnLayout::Simd4xN
113                    ? GMX_SIMD_REAL_WIDTH
114                    : (layout == NbnxnLayout::Simd2xNN ? GMX_SIMD_REAL_WIDTH / 2 : c_nbnxnCpuIClusterSize);
115 }
116
117 /*! \brief Returns the j-cluster index given the i-cluster index.
118  *
119  * \tparam    jClusterSize      The number of atoms in a j-cluster
120  * \tparam    jSubClusterIndex  The j-sub-cluster index (0/1), used when size(j-cluster) <
121  * size(i-cluster) \param[in] ci                The i-cluster index
122  */
123 template<int jClusterSize, int jSubClusterIndex>
124 static inline int cjFromCi(int ci)
125 {
126     static_assert(jClusterSize == c_nbnxnCpuIClusterSize / 2 || jClusterSize == c_nbnxnCpuIClusterSize
127                           || jClusterSize == c_nbnxnCpuIClusterSize * 2,
128                   "Only j-cluster sizes 2, 4 and 8 are currently implemented");
129
130     static_assert(jSubClusterIndex == 0 || jSubClusterIndex == 1,
131                   "Only sub-cluster indices 0 and 1 are supported");
132
133     if (jClusterSize == c_nbnxnCpuIClusterSize / 2)
134     {
135         if (jSubClusterIndex == 0)
136         {
137             return ci << 1;
138         }
139         else
140         {
141             return ((ci + 1) << 1) - 1;
142         }
143     }
144     else if (jClusterSize == c_nbnxnCpuIClusterSize)
145     {
146         return ci;
147     }
148     else
149     {
150         return ci >> 1;
151     }
152 }
153
154 /*! \brief Returns the j-cluster index given the i-cluster index.
155  *
156  * \tparam    layout            The pair-list layout
157  * \tparam    jSubClusterIndex  The j-sub-cluster index (0/1), used when size(j-cluster) <
158  * size(i-cluster) \param[in] ci                The i-cluster index
159  */
160 template<NbnxnLayout layout, int jSubClusterIndex>
161 static inline int cjFromCi(int ci)
162 {
163     constexpr int clusterSize = jClusterSize<layout>();
164
165     return cjFromCi<clusterSize, jSubClusterIndex>(ci);
166 }
167
168 /* Returns the nbnxn coordinate data index given the i-cluster index */
169 template<NbnxnLayout layout>
170 static inline int xIndexFromCi(int ci)
171 {
172     constexpr int clusterSize = jClusterSize<layout>();
173
174     static_assert(clusterSize == c_nbnxnCpuIClusterSize / 2 || clusterSize == c_nbnxnCpuIClusterSize
175                           || clusterSize == c_nbnxnCpuIClusterSize * 2,
176                   "Only j-cluster sizes 2, 4 and 8 are currently implemented");
177
178     if (clusterSize <= c_nbnxnCpuIClusterSize)
179     {
180         /* Coordinates are stored packed in groups of 4 */
181         return ci * STRIDE_P4;
182     }
183     else
184     {
185         /* Coordinates packed in 8, i-cluster size is half the packing width */
186         return (ci >> 1) * STRIDE_P8 + (ci & 1) * (c_packX8 >> 1);
187     }
188 }
189
190 /* Returns the nbnxn coordinate data index given the j-cluster index */
191 template<NbnxnLayout layout>
192 static inline int xIndexFromCj(int cj)
193 {
194     constexpr int clusterSize = jClusterSize<layout>();
195
196     static_assert(clusterSize == c_nbnxnCpuIClusterSize / 2 || clusterSize == c_nbnxnCpuIClusterSize
197                           || clusterSize == c_nbnxnCpuIClusterSize * 2,
198                   "Only j-cluster sizes 2, 4 and 8 are currently implemented");
199
200     if (clusterSize == c_nbnxnCpuIClusterSize / 2)
201     {
202         /* Coordinates are stored packed in groups of 4 */
203         return (cj >> 1) * STRIDE_P4 + (cj & 1) * (c_packX4 >> 1);
204     }
205     else if (clusterSize == c_nbnxnCpuIClusterSize)
206     {
207         /* Coordinates are stored packed in groups of 4 */
208         return cj * STRIDE_P4;
209     }
210     else
211     {
212         /* Coordinates are stored packed in groups of 8 */
213         return cj * STRIDE_P8;
214     }
215 }
216 #endif // GMX_SIMD
217
218
219 void nbnxn_init_pairlist_fep(t_nblist* nl)
220 {
221     nl->type      = GMX_NBLIST_INTERACTION_FREE_ENERGY;
222     nl->igeometry = GMX_NBLIST_GEOMETRY_PARTICLE_PARTICLE;
223     /* The interaction functions are set in the free energy kernel fuction */
224     nl->ivdw     = -1;
225     nl->ivdwmod  = -1;
226     nl->ielec    = -1;
227     nl->ielecmod = -1;
228
229     nl->maxnri   = 0;
230     nl->maxnrj   = 0;
231     nl->nri      = 0;
232     nl->nrj      = 0;
233     nl->iinr     = nullptr;
234     nl->gid      = nullptr;
235     nl->shift    = nullptr;
236     nl->jindex   = nullptr;
237     nl->jjnr     = nullptr;
238     nl->excl_fep = nullptr;
239 }
240
241 static void init_buffer_flags(nbnxn_buffer_flags_t* flags, int natoms)
242 {
243     flags->nflag = (natoms + NBNXN_BUFFERFLAG_SIZE - 1) / NBNXN_BUFFERFLAG_SIZE;
244     if (flags->nflag > flags->flag_nalloc)
245     {
246         flags->flag_nalloc = over_alloc_large(flags->nflag);
247         srenew(flags->flag, flags->flag_nalloc);
248     }
249     for (int b = 0; b < flags->nflag; b++)
250     {
251         bitmask_clear(&(flags->flag[b]));
252     }
253 }
254
255 /* Returns the pair-list cutoff between a bounding box and a grid cell given an atom-to-atom pair-list cutoff
256  *
257  * Given a cutoff distance between atoms, this functions returns the cutoff
258  * distance2 between a bounding box of a group of atoms and a grid cell.
259  * Since atoms can be geometrically outside of the cell they have been
260  * assigned to (when atom groups instead of individual atoms are assigned
261  * to cells), this distance returned can be larger than the input.
262  */
263 static real listRangeForBoundingBoxToGridCell(real rlist, const Grid::Dimensions& gridDims)
264 {
265     return rlist + gridDims.maxAtomGroupRadius;
266 }
267 /* Returns the pair-list cutoff between a grid cells given an atom-to-atom pair-list cutoff
268  *
269  * Given a cutoff distance between atoms, this functions returns the cutoff
270  * distance2 between two grid cells.
271  * Since atoms can be geometrically outside of the cell they have been
272  * assigned to (when atom groups instead of individual atoms are assigned
273  * to cells), this distance returned can be larger than the input.
274  */
275 static real listRangeForGridCellToGridCell(real                    rlist,
276                                            const Grid::Dimensions& iGridDims,
277                                            const Grid::Dimensions& jGridDims)
278 {
279     return rlist + iGridDims.maxAtomGroupRadius + jGridDims.maxAtomGroupRadius;
280 }
281
282 /* Determines the cell range along one dimension that
283  * the bounding box b0 - b1 sees.
284  */
285 template<int dim>
286 static void
287 get_cell_range(real b0, real b1, const Grid::Dimensions& jGridDims, real d2, real rlist, int* cf, int* cl)
288 {
289     real listRangeBBToCell2 = gmx::square(listRangeForBoundingBoxToGridCell(rlist, jGridDims));
290     real distanceInCells    = (b0 - jGridDims.lowerCorner[dim]) * jGridDims.invCellSize[dim];
291     *cf                     = std::max(static_cast<int>(distanceInCells), 0);
292
293     while (*cf > 0
294            && d2 + gmx::square((b0 - jGridDims.lowerCorner[dim]) - (*cf - 1 + 1) * jGridDims.cellSize[dim])
295                       < listRangeBBToCell2)
296     {
297         (*cf)--;
298     }
299
300     *cl = std::min(static_cast<int>((b1 - jGridDims.lowerCorner[dim]) * jGridDims.invCellSize[dim]),
301                    jGridDims.numCells[dim] - 1);
302     while (*cl < jGridDims.numCells[dim] - 1
303            && d2 + gmx::square((*cl + 1) * jGridDims.cellSize[dim] - (b1 - jGridDims.lowerCorner[dim]))
304                       < listRangeBBToCell2)
305     {
306         (*cl)++;
307     }
308 }
309
310 /* Reference code calculating the distance^2 between two bounding boxes */
311 /*
312    static float box_dist2(float bx0, float bx1, float by0,
313                        float by1, float bz0, float bz1,
314                        const BoundingBox *bb)
315    {
316     float d2;
317     float dl, dh, dm, dm0;
318
319     d2 = 0;
320
321     dl  = bx0 - bb->upper.x;
322     dh  = bb->lower.x - bx1;
323     dm  = std::max(dl, dh);
324     dm0 = std::max(dm, 0.0f);
325     d2 += dm0*dm0;
326
327     dl  = by0 - bb->upper.y;
328     dh  = bb->lower.y - by1;
329     dm  = std::max(dl, dh);
330     dm0 = std::max(dm, 0.0f);
331     d2 += dm0*dm0;
332
333     dl  = bz0 - bb->upper.z;
334     dh  = bb->lower.z - bz1;
335     dm  = std::max(dl, dh);
336     dm0 = std::max(dm, 0.0f);
337     d2 += dm0*dm0;
338
339     return d2;
340    }
341  */
342
343 #if !NBNXN_SEARCH_BB_SIMD4
344
345 /*! \brief Plain C code calculating the distance^2 between two bounding boxes in xyz0 format
346  *
347  * \param[in] bb_i  First bounding box
348  * \param[in] bb_j  Second bounding box
349  */
350 static float clusterBoundingBoxDistance2(const BoundingBox& bb_i, const BoundingBox& bb_j)
351 {
352     float dl  = bb_i.lower.x - bb_j.upper.x;
353     float dh  = bb_j.lower.x - bb_i.upper.x;
354     float dm  = std::max(dl, dh);
355     float dm0 = std::max(dm, 0.0F);
356     float d2  = dm0 * dm0;
357
358     dl  = bb_i.lower.y - bb_j.upper.y;
359     dh  = bb_j.lower.y - bb_i.upper.y;
360     dm  = std::max(dl, dh);
361     dm0 = std::max(dm, 0.0F);
362     d2 += dm0 * dm0;
363
364     dl  = bb_i.lower.z - bb_j.upper.z;
365     dh  = bb_j.lower.z - bb_i.upper.z;
366     dm  = std::max(dl, dh);
367     dm0 = std::max(dm, 0.0F);
368     d2 += dm0 * dm0;
369
370     return d2;
371 }
372
373 #else /* NBNXN_SEARCH_BB_SIMD4 */
374
375 /*! \brief 4-wide SIMD code calculating the distance^2 between two bounding boxes in xyz0 format
376  *
377  * \param[in] bb_i  First bounding box, should be aligned for 4-wide SIMD
378  * \param[in] bb_j  Second bounding box, should be aligned for 4-wide SIMD
379  */
380 static float clusterBoundingBoxDistance2(const BoundingBox& bb_i, const BoundingBox& bb_j)
381 {
382     // TODO: During SIMDv2 transition only some archs use namespace (remove when done)
383     using namespace gmx;
384
385     const Simd4Float bb_i_S0 = load4(bb_i.lower.ptr());
386     const Simd4Float bb_i_S1 = load4(bb_i.upper.ptr());
387     const Simd4Float bb_j_S0 = load4(bb_j.lower.ptr());
388     const Simd4Float bb_j_S1 = load4(bb_j.upper.ptr());
389
390     const Simd4Float dl_S = bb_i_S0 - bb_j_S1;
391     const Simd4Float dh_S = bb_j_S0 - bb_i_S1;
392
393     const Simd4Float dm_S  = max(dl_S, dh_S);
394     const Simd4Float dm0_S = max(dm_S, simd4SetZeroF());
395
396     return dotProduct(dm0_S, dm0_S);
397 }
398
399 /* Calculate bb bounding distances of bb_i[si,...,si+3] and store them in d2 */
400 template<int boundingBoxStart>
401 static inline void gmx_simdcall clusterBoundingBoxDistance2_xxxx_simd4_inner(const float*     bb_i,
402                                                                              float*           d2,
403                                                                              const Simd4Float xj_l,
404                                                                              const Simd4Float yj_l,
405                                                                              const Simd4Float zj_l,
406                                                                              const Simd4Float xj_h,
407                                                                              const Simd4Float yj_h,
408                                                                              const Simd4Float zj_h)
409 {
410     constexpr int stride = c_packedBoundingBoxesDimSize;
411
412     const int shi = boundingBoxStart * Nbnxm::c_numBoundingBoxBounds1D * DIM;
413
414     const Simd4Float zero = setZero();
415
416     const Simd4Float xi_l = load4(bb_i + shi + 0 * stride);
417     const Simd4Float yi_l = load4(bb_i + shi + 1 * stride);
418     const Simd4Float zi_l = load4(bb_i + shi + 2 * stride);
419     const Simd4Float xi_h = load4(bb_i + shi + 3 * stride);
420     const Simd4Float yi_h = load4(bb_i + shi + 4 * stride);
421     const Simd4Float zi_h = load4(bb_i + shi + 5 * stride);
422
423     const Simd4Float dx_0 = xi_l - xj_h;
424     const Simd4Float dy_0 = yi_l - yj_h;
425     const Simd4Float dz_0 = zi_l - zj_h;
426
427     const Simd4Float dx_1 = xj_l - xi_h;
428     const Simd4Float dy_1 = yj_l - yi_h;
429     const Simd4Float dz_1 = zj_l - zi_h;
430
431     const Simd4Float mx = max(dx_0, dx_1);
432     const Simd4Float my = max(dy_0, dy_1);
433     const Simd4Float mz = max(dz_0, dz_1);
434
435     const Simd4Float m0x = max(mx, zero);
436     const Simd4Float m0y = max(my, zero);
437     const Simd4Float m0z = max(mz, zero);
438
439     const Simd4Float d2x = m0x * m0x;
440     const Simd4Float d2y = m0y * m0y;
441     const Simd4Float d2z = m0z * m0z;
442
443     const Simd4Float d2s = d2x + d2y;
444     const Simd4Float d2t = d2s + d2z;
445
446     store4(d2 + boundingBoxStart, d2t);
447 }
448
449 /* 4-wide SIMD code for nsi bb distances for bb format xxxxyyyyzzzz */
450 static void clusterBoundingBoxDistance2_xxxx_simd4(const float* bb_j, const int nsi, const float* bb_i, float* d2)
451 {
452     constexpr int stride = c_packedBoundingBoxesDimSize;
453
454     // TODO: During SIMDv2 transition only some archs use namespace (remove when done)
455     using namespace gmx;
456
457     const Simd4Float xj_l = Simd4Float(bb_j[0 * stride]);
458     const Simd4Float yj_l = Simd4Float(bb_j[1 * stride]);
459     const Simd4Float zj_l = Simd4Float(bb_j[2 * stride]);
460     const Simd4Float xj_h = Simd4Float(bb_j[3 * stride]);
461     const Simd4Float yj_h = Simd4Float(bb_j[4 * stride]);
462     const Simd4Float zj_h = Simd4Float(bb_j[5 * stride]);
463
464     /* Here we "loop" over si (0,stride) from 0 to nsi with step stride.
465      * But as we know the number of iterations is 1 or 2, we unroll manually.
466      */
467     clusterBoundingBoxDistance2_xxxx_simd4_inner<0>(bb_i, d2, xj_l, yj_l, zj_l, xj_h, yj_h, zj_h);
468     if (stride < nsi)
469     {
470         clusterBoundingBoxDistance2_xxxx_simd4_inner<stride>(bb_i, d2, xj_l, yj_l, zj_l, xj_h, yj_h, zj_h);
471     }
472 }
473
474 #endif /* NBNXN_SEARCH_BB_SIMD4 */
475
476
477 /* Returns if any atom pair from two clusters is within distance sqrt(rlist2) */
478 static inline gmx_bool
479 clusterpair_in_range(const NbnxnPairlistGpuWork& work, int si, int csj, int stride, const real* x_j, real rlist2)
480 {
481 #if !GMX_SIMD4_HAVE_REAL
482
483     /* Plain C version.
484      * All coordinates are stored as xyzxyz...
485      */
486
487     const real* x_i = work.iSuperClusterData.x.data();
488
489     for (int i = 0; i < c_nbnxnGpuClusterSize; i++)
490     {
491         int i0 = (si * c_nbnxnGpuClusterSize + i) * DIM;
492         for (int j = 0; j < c_nbnxnGpuClusterSize; j++)
493         {
494             int j0 = (csj * c_nbnxnGpuClusterSize + j) * stride;
495
496             real d2 = gmx::square(x_i[i0] - x_j[j0]) + gmx::square(x_i[i0 + 1] - x_j[j0 + 1])
497                       + gmx::square(x_i[i0 + 2] - x_j[j0 + 2]);
498
499             if (d2 < rlist2)
500             {
501                 return TRUE;
502             }
503         }
504     }
505
506     return FALSE;
507
508 #else /* !GMX_SIMD4_HAVE_REAL */
509
510     /* 4-wide SIMD version.
511      * The coordinates x_i are stored as xxxxyyyy..., x_j is stored xyzxyz...
512      * Using 8-wide AVX(2) is not faster on Intel Sandy Bridge and Haswell.
513      */
514     static_assert(c_nbnxnGpuClusterSize == 8 || c_nbnxnGpuClusterSize == 4,
515                   "A cluster is hard-coded to 4/8 atoms.");
516
517     Simd4Real rc2_S = Simd4Real(rlist2);
518
519     const real* x_i = work.iSuperClusterData.xSimd.data();
520
521     int       dim_stride = c_nbnxnGpuClusterSize * DIM;
522     Simd4Real ix_S0      = load4(x_i + si * dim_stride + 0 * GMX_SIMD4_WIDTH);
523     Simd4Real iy_S0      = load4(x_i + si * dim_stride + 1 * GMX_SIMD4_WIDTH);
524     Simd4Real iz_S0      = load4(x_i + si * dim_stride + 2 * GMX_SIMD4_WIDTH);
525
526     Simd4Real ix_S1, iy_S1, iz_S1;
527     if (c_nbnxnGpuClusterSize == 8)
528     {
529         ix_S1 = load4(x_i + si * dim_stride + 3 * GMX_SIMD4_WIDTH);
530         iy_S1 = load4(x_i + si * dim_stride + 4 * GMX_SIMD4_WIDTH);
531         iz_S1 = load4(x_i + si * dim_stride + 5 * GMX_SIMD4_WIDTH);
532     }
533     /* We loop from the outer to the inner particles to maximize
534      * the chance that we find a pair in range quickly and return.
535      */
536     int j0 = csj * c_nbnxnGpuClusterSize;
537     int j1 = j0 + c_nbnxnGpuClusterSize - 1;
538     while (j0 < j1)
539     {
540         Simd4Real jx0_S, jy0_S, jz0_S;
541         Simd4Real jx1_S, jy1_S, jz1_S;
542
543         Simd4Real dx_S0, dy_S0, dz_S0;
544         Simd4Real dx_S1, dy_S1, dz_S1;
545         Simd4Real dx_S2, dy_S2, dz_S2;
546         Simd4Real dx_S3, dy_S3, dz_S3;
547
548         Simd4Real rsq_S0;
549         Simd4Real rsq_S1;
550         Simd4Real rsq_S2;
551         Simd4Real rsq_S3;
552
553         Simd4Bool wco_S0;
554         Simd4Bool wco_S1;
555         Simd4Bool wco_S2;
556         Simd4Bool wco_S3;
557         Simd4Bool wco_any_S01, wco_any_S23, wco_any_S;
558
559         jx0_S = Simd4Real(x_j[j0 * stride + 0]);
560         jy0_S = Simd4Real(x_j[j0 * stride + 1]);
561         jz0_S = Simd4Real(x_j[j0 * stride + 2]);
562
563         jx1_S = Simd4Real(x_j[j1 * stride + 0]);
564         jy1_S = Simd4Real(x_j[j1 * stride + 1]);
565         jz1_S = Simd4Real(x_j[j1 * stride + 2]);
566
567         /* Calculate distance */
568         dx_S0 = ix_S0 - jx0_S;
569         dy_S0 = iy_S0 - jy0_S;
570         dz_S0 = iz_S0 - jz0_S;
571         dx_S2 = ix_S0 - jx1_S;
572         dy_S2 = iy_S0 - jy1_S;
573         dz_S2 = iz_S0 - jz1_S;
574         if (c_nbnxnGpuClusterSize == 8)
575         {
576             dx_S1 = ix_S1 - jx0_S;
577             dy_S1 = iy_S1 - jy0_S;
578             dz_S1 = iz_S1 - jz0_S;
579             dx_S3 = ix_S1 - jx1_S;
580             dy_S3 = iy_S1 - jy1_S;
581             dz_S3 = iz_S1 - jz1_S;
582         }
583
584         /* rsq = dx*dx+dy*dy+dz*dz */
585         rsq_S0 = norm2(dx_S0, dy_S0, dz_S0);
586         rsq_S2 = norm2(dx_S2, dy_S2, dz_S2);
587         if (c_nbnxnGpuClusterSize == 8)
588         {
589             rsq_S1 = norm2(dx_S1, dy_S1, dz_S1);
590             rsq_S3 = norm2(dx_S3, dy_S3, dz_S3);
591         }
592
593         wco_S0 = (rsq_S0 < rc2_S);
594         wco_S2 = (rsq_S2 < rc2_S);
595         if (c_nbnxnGpuClusterSize == 8)
596         {
597             wco_S1 = (rsq_S1 < rc2_S);
598             wco_S3 = (rsq_S3 < rc2_S);
599         }
600         if (c_nbnxnGpuClusterSize == 8)
601         {
602             wco_any_S01 = wco_S0 || wco_S1;
603             wco_any_S23 = wco_S2 || wco_S3;
604             wco_any_S   = wco_any_S01 || wco_any_S23;
605         }
606         else
607         {
608             wco_any_S = wco_S0 || wco_S2;
609         }
610
611         if (anyTrue(wco_any_S))
612         {
613             return TRUE;
614         }
615
616         j0++;
617         j1--;
618     }
619
620     return FALSE;
621
622 #endif /* !GMX_SIMD4_HAVE_REAL */
623 }
624
625 /* Returns the j-cluster index for index cjIndex in a cj list */
626 static inline int nblCj(gmx::ArrayRef<const nbnxn_cj_t> cjList, int cjIndex)
627 {
628     return cjList[cjIndex].cj;
629 }
630
631 /* Returns the j-cluster index for index cjIndex in a cj4 list */
632 static inline int nblCj(gmx::ArrayRef<const nbnxn_cj4_t> cj4List, int cjIndex)
633 {
634     return cj4List[cjIndex / c_nbnxnGpuJgroupSize].cj[cjIndex & (c_nbnxnGpuJgroupSize - 1)];
635 }
636
637 /* Returns the i-interaction mask of the j sub-cell for index cj_ind */
638 static unsigned int nbl_imask0(const NbnxnPairlistGpu* nbl, int cj_ind)
639 {
640     return nbl->cj4[cj_ind / c_nbnxnGpuJgroupSize].imei[0].imask;
641 }
642
643 NbnxnPairlistCpu::NbnxnPairlistCpu() :
644     na_ci(c_nbnxnCpuIClusterSize),
645     na_cj(0),
646     rlist(0),
647     ncjInUse(0),
648     nci_tot(0),
649     work(std::make_unique<NbnxnPairlistCpuWork>())
650 {
651 }
652
653 NbnxnPairlistGpu::NbnxnPairlistGpu(gmx::PinningPolicy pinningPolicy) :
654     na_ci(c_nbnxnGpuClusterSize),
655     na_cj(c_nbnxnGpuClusterSize),
656     na_sc(c_gpuNumClusterPerCell * c_nbnxnGpuClusterSize),
657     rlist(0),
658     sci({}, { pinningPolicy }),
659     cj4({}, { pinningPolicy }),
660     excl({}, { pinningPolicy }),
661     nci_tot(0),
662     work(std::make_unique<NbnxnPairlistGpuWork>())
663 {
664     static_assert(c_nbnxnGpuNumClusterPerSupercluster == c_gpuNumClusterPerCell,
665                   "The search code assumes that the a super-cluster matches a search grid cell");
666
667     static_assert(sizeof(cj4[0].imei[0].imask) * 8 >= c_nbnxnGpuJgroupSize * c_gpuNumClusterPerCell,
668                   "The i super-cluster cluster interaction mask does not contain a sufficient "
669                   "number of bits");
670
671     static_assert(sizeof(excl[0]) * 8 >= c_nbnxnGpuJgroupSize * c_gpuNumClusterPerCell,
672                   "The GPU exclusion mask does not contain a sufficient number of bits");
673
674     // We always want a first entry without any exclusions
675     excl.resize(1);
676 }
677
678 // TODO: Move to pairlistset.cpp
679 PairlistSet::PairlistSet(const InteractionLocality locality, const PairlistParams& pairlistParams) :
680     locality_(locality),
681     params_(pairlistParams)
682 {
683     isCpuType_ = (params_.pairlistType == PairlistType::Simple4x2
684                   || params_.pairlistType == PairlistType::Simple4x4
685                   || params_.pairlistType == PairlistType::Simple4x8);
686     // Currently GPU lists are always combined
687     combineLists_ = !isCpuType_;
688
689     const int numLists = gmx_omp_nthreads_get(emntNonbonded);
690
691     if (!combineLists_ && numLists > NBNXN_BUFFERFLAG_MAX_THREADS)
692     {
693         gmx_fatal(FARGS,
694                   "%d OpenMP threads were requested. Since the non-bonded force buffer reduction "
695                   "is prohibitively slow with more than %d threads, we do not allow this. Use %d "
696                   "or less OpenMP threads.",
697                   numLists, NBNXN_BUFFERFLAG_MAX_THREADS, NBNXN_BUFFERFLAG_MAX_THREADS);
698     }
699
700     if (isCpuType_)
701     {
702         cpuLists_.resize(numLists);
703         if (numLists > 1)
704         {
705             cpuListsWork_.resize(numLists);
706         }
707     }
708     else
709     {
710         /* Only list 0 is used on the GPU, use normal allocation for i>0 */
711         gpuLists_.emplace_back(gmx::PinningPolicy::PinnedIfSupported);
712         /* Lists 0 to numLists are use for constructing lists in parallel
713          * on the CPU using numLists threads (and then merged into list 0).
714          */
715         for (int i = 1; i < numLists; i++)
716         {
717             gpuLists_.emplace_back(gmx::PinningPolicy::CannotBePinned);
718         }
719     }
720     if (params_.haveFep)
721     {
722         fepLists_.resize(numLists);
723
724         /* Execute in order to avoid memory interleaving between threads */
725 #pragma omp parallel for num_threads(numLists) schedule(static)
726         for (int i = 0; i < numLists; i++)
727         {
728             try
729             {
730                 /* We used to allocate all normal lists locally on each thread
731                  * as well. The question is if allocating the object on the
732                  * master thread (but all contained list memory thread local)
733                  * impacts performance.
734                  */
735                 fepLists_[i] = std::make_unique<t_nblist>();
736                 nbnxn_init_pairlist_fep(fepLists_[i].get());
737             }
738             GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
739         }
740     }
741 }
742
743 /* Print statistics of a pair list, used for debug output */
744 static void print_nblist_statistics(FILE*                   fp,
745                                     const NbnxnPairlistCpu& nbl,
746                                     const Nbnxm::GridSet&   gridSet,
747                                     const real              rl)
748 {
749     const Grid&             grid = gridSet.grids()[0];
750     const Grid::Dimensions& dims = grid.dimensions();
751
752     fprintf(fp, "nbl nci %zu ncj %d\n", nbl.ci.size(), nbl.ncjInUse);
753     const int numAtomsJCluster = grid.geometry().numAtomsJCluster;
754     const double numAtomsPerCell = nbl.ncjInUse / static_cast<double>(grid.numCells()) * numAtomsJCluster;
755     fprintf(fp, "nbl na_cj %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n", nbl.na_cj, rl,
756             nbl.ncjInUse, nbl.ncjInUse / static_cast<double>(grid.numCells()), numAtomsPerCell,
757             numAtomsPerCell
758                     / (0.5 * 4.0 / 3.0 * M_PI * rl * rl * rl * grid.numCells() * numAtomsJCluster
759                        / (dims.gridSize[XX] * dims.gridSize[YY] * dims.gridSize[ZZ])));
760
761     fprintf(fp, "nbl average j cell list length %.1f\n",
762             0.25 * nbl.ncjInUse / std::max(static_cast<double>(nbl.ci.size()), 1.0));
763
764     int cs[SHIFTS] = { 0 };
765     int npexcl     = 0;
766     for (const nbnxn_ci_t& ciEntry : nbl.ci)
767     {
768         cs[ciEntry.shift & NBNXN_CI_SHIFT] += ciEntry.cj_ind_end - ciEntry.cj_ind_start;
769
770         int j = ciEntry.cj_ind_start;
771         while (j < ciEntry.cj_ind_end && nbl.cj[j].excl != NBNXN_INTERACTION_MASK_ALL)
772         {
773             npexcl++;
774             j++;
775         }
776     }
777     fprintf(fp, "nbl cell pairs, total: %zu excl: %d %.1f%%\n", nbl.cj.size(), npexcl,
778             100 * npexcl / std::max(static_cast<double>(nbl.cj.size()), 1.0));
779     for (int s = 0; s < SHIFTS; s++)
780     {
781         if (cs[s] > 0)
782         {
783             fprintf(fp, "nbl shift %2d ncj %3d\n", s, cs[s]);
784         }
785     }
786 }
787
788 /* Print statistics of a pair lists, used for debug output */
789 static void print_nblist_statistics(FILE*                   fp,
790                                     const NbnxnPairlistGpu& nbl,
791                                     const Nbnxm::GridSet&   gridSet,
792                                     const real              rl)
793 {
794     const Grid&             grid = gridSet.grids()[0];
795     const Grid::Dimensions& dims = grid.dimensions();
796
797     fprintf(fp, "nbl nsci %zu ncj4 %zu nsi %d excl4 %zu\n", nbl.sci.size(), nbl.cj4.size(),
798             nbl.nci_tot, nbl.excl.size());
799     const int numAtomsCluster = grid.geometry().numAtomsICluster;
800     const double numAtomsPerCell = nbl.nci_tot / static_cast<double>(grid.numClusters()) * numAtomsCluster;
801     fprintf(fp, "nbl na_c %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n", nbl.na_ci, rl,
802             nbl.nci_tot, nbl.nci_tot / static_cast<double>(grid.numClusters()), numAtomsPerCell,
803             numAtomsPerCell
804                     / (0.5 * 4.0 / 3.0 * M_PI * rl * rl * rl * grid.numClusters() * numAtomsCluster
805                        / (dims.gridSize[XX] * dims.gridSize[YY] * dims.gridSize[ZZ])));
806
807     double sum_nsp                       = 0;
808     double sum_nsp2                      = 0;
809     int    nsp_max                       = 0;
810     int    c[c_gpuNumClusterPerCell + 1] = { 0 };
811     for (const nbnxn_sci_t& sci : nbl.sci)
812     {
813         int nsp = 0;
814         for (int j4 = sci.cj4_ind_start; j4 < sci.cj4_ind_end; j4++)
815         {
816             for (int j = 0; j < c_nbnxnGpuJgroupSize; j++)
817             {
818                 int b = 0;
819                 for (int si = 0; si < c_gpuNumClusterPerCell; si++)
820                 {
821                     if (nbl.cj4[j4].imei[0].imask & (1U << (j * c_gpuNumClusterPerCell + si)))
822                     {
823                         b++;
824                     }
825                 }
826                 nsp += b;
827                 c[b]++;
828             }
829         }
830         sum_nsp += nsp;
831         sum_nsp2 += nsp * nsp;
832         nsp_max = std::max(nsp_max, nsp);
833     }
834     if (!nbl.sci.empty())
835     {
836         sum_nsp /= nbl.sci.size();
837         sum_nsp2 /= nbl.sci.size();
838     }
839     fprintf(fp, "nbl #cluster-pairs: av %.1f stddev %.1f max %d\n", sum_nsp,
840             std::sqrt(sum_nsp2 - sum_nsp * sum_nsp), nsp_max);
841
842     if (!nbl.cj4.empty())
843     {
844         for (int b = 0; b <= c_gpuNumClusterPerCell; b++)
845         {
846             fprintf(fp, "nbl j-list #i-subcell %d %7d %4.1f\n", b, c[b],
847                     100.0 * c[b] / size_t{ nbl.cj4.size() * c_nbnxnGpuJgroupSize });
848         }
849     }
850 }
851
852 /* Returns a reference to the exclusion mask for j-cluster-group \p cj4 and warp \p warp
853  * Generates a new exclusion entry when the j-cluster-group uses
854  * the default all-interaction mask at call time, so the returned mask
855  * can be modified when needed.
856  */
857 static nbnxn_excl_t& get_exclusion_mask(NbnxnPairlistGpu* nbl, int cj4, int warp)
858 {
859     if (nbl->cj4[cj4].imei[warp].excl_ind == 0)
860     {
861         /* No exclusions set, make a new list entry */
862         const size_t oldSize = nbl->excl.size();
863         GMX_ASSERT(oldSize >= 1, "We should always have entry [0]");
864         /* Add entry with default values: no exclusions */
865         nbl->excl.resize(oldSize + 1);
866         nbl->cj4[cj4].imei[warp].excl_ind = oldSize;
867     }
868
869     return nbl->excl[nbl->cj4[cj4].imei[warp].excl_ind];
870 }
871
872 /* Sets self exclusions and excludes half of the double pairs in the self cluster-pair \p nbl->cj4[cj4Index].cj[jOffsetInGroup]
873  *
874  * \param[in,out] nbl             The cluster pair list
875  * \param[in]     cj4Index        The j-cluster group index into \p nbl->cj4
876  * \param[in]     jOffsetInGroup  The j-entry offset in \p nbl->cj4[cj4Index]
877  * \param[in]     iClusterInCell  The i-cluster index in the cell
878  */
879 static void setSelfAndNewtonExclusionsGpu(NbnxnPairlistGpu* nbl,
880                                           const int         cj4Index,
881                                           const int         jOffsetInGroup,
882                                           const int         iClusterInCell)
883 {
884     constexpr int numJatomsPerPart = c_nbnxnGpuClusterSize / c_nbnxnGpuClusterpairSplit;
885
886     /* The exclusions are stored separately for each part of the split */
887     for (int part = 0; part < c_nbnxnGpuClusterpairSplit; part++)
888     {
889         const int jOffset = part * numJatomsPerPart;
890         /* Make a new exclusion mask entry for each part, if we don't already have one yet */
891         nbnxn_excl_t& excl = get_exclusion_mask(nbl, cj4Index, part);
892
893         /* Set all bits with j-index <= i-index */
894         for (int jIndexInPart = 0; jIndexInPart < numJatomsPerPart; jIndexInPart++)
895         {
896             for (int i = jOffset + jIndexInPart; i < c_nbnxnGpuClusterSize; i++)
897             {
898                 excl.pair[jIndexInPart * c_nbnxnGpuClusterSize + i] &=
899                         ~(1U << (jOffsetInGroup * c_gpuNumClusterPerCell + iClusterInCell));
900             }
901         }
902     }
903 }
904
905 /* Returns a diagonal or off-diagonal interaction mask for plain C lists */
906 static unsigned int get_imask(gmx_bool rdiag, int ci, int cj)
907 {
908     return (rdiag && ci == cj ? NBNXN_INTERACTION_MASK_DIAG : NBNXN_INTERACTION_MASK_ALL);
909 }
910
911 /* Returns a diagonal or off-diagonal interaction mask for cj-size=2 */
912 gmx_unused static unsigned int get_imask_simd_j2(gmx_bool rdiag, int ci, int cj)
913 {
914     return (rdiag && ci * 2 == cj ? NBNXN_INTERACTION_MASK_DIAG_J2_0
915                                   : (rdiag && ci * 2 + 1 == cj ? NBNXN_INTERACTION_MASK_DIAG_J2_1
916                                                                : NBNXN_INTERACTION_MASK_ALL));
917 }
918
919 /* Returns a diagonal or off-diagonal interaction mask for cj-size=4 */
920 gmx_unused static unsigned int get_imask_simd_j4(gmx_bool rdiag, int ci, int cj)
921 {
922     return (rdiag && ci == cj ? NBNXN_INTERACTION_MASK_DIAG : NBNXN_INTERACTION_MASK_ALL);
923 }
924
925 /* Returns a diagonal or off-diagonal interaction mask for cj-size=8 */
926 gmx_unused static unsigned int get_imask_simd_j8(gmx_bool rdiag, int ci, int cj)
927 {
928     return (rdiag && ci == cj * 2 ? NBNXN_INTERACTION_MASK_DIAG_J8_0
929                                   : (rdiag && ci == cj * 2 + 1 ? NBNXN_INTERACTION_MASK_DIAG_J8_1
930                                                                : NBNXN_INTERACTION_MASK_ALL));
931 }
932
933 #if GMX_SIMD
934 #    if GMX_SIMD_REAL_WIDTH == 2
935 #        define get_imask_simd_4xn get_imask_simd_j2
936 #    endif
937 #    if GMX_SIMD_REAL_WIDTH == 4
938 #        define get_imask_simd_4xn get_imask_simd_j4
939 #    endif
940 #    if GMX_SIMD_REAL_WIDTH == 8
941 #        define get_imask_simd_4xn get_imask_simd_j8
942 #        define get_imask_simd_2xnn get_imask_simd_j4
943 #    endif
944 #    if GMX_SIMD_REAL_WIDTH == 16
945 #        define get_imask_simd_2xnn get_imask_simd_j8
946 #    endif
947 #endif
948
949 /* Plain C code for checking and adding cluster-pairs to the list.
950  *
951  * \param[in]     gridj               The j-grid
952  * \param[in,out] nbl                 The pair-list to store the cluster pairs in
953  * \param[in]     icluster            The index of the i-cluster
954  * \param[in]     jclusterFirst       The first cluster in the j-range
955  * \param[in]     jclusterLast        The last cluster in the j-range
956  * \param[in]     excludeSubDiagonal  Exclude atom pairs with i-index > j-index
957  * \param[in]     x_j                 Coordinates for the j-atom, in xyz format
958  * \param[in]     rlist2              The squared list cut-off
959  * \param[in]     rbb2                The squared cut-off for putting cluster-pairs in the list based on bounding box distance only
960  * \param[in,out] numDistanceChecks   The number of distance checks performed
961  */
962 static void makeClusterListSimple(const Grid&       jGrid,
963                                   NbnxnPairlistCpu* nbl,
964                                   int               icluster,
965                                   int               jclusterFirst,
966                                   int               jclusterLast,
967                                   bool              excludeSubDiagonal,
968                                   const real* gmx_restrict x_j,
969                                   real                     rlist2,
970                                   float                    rbb2,
971                                   int* gmx_restrict numDistanceChecks)
972 {
973     const BoundingBox* gmx_restrict bb_ci = nbl->work->iClusterData.bb.data();
974     const real* gmx_restrict x_ci         = nbl->work->iClusterData.x.data();
975
976     gmx_bool InRange;
977
978     InRange = FALSE;
979     while (!InRange && jclusterFirst <= jclusterLast)
980     {
981         real d2 = clusterBoundingBoxDistance2(bb_ci[0], jGrid.jBoundingBoxes()[jclusterFirst]);
982         *numDistanceChecks += 2;
983
984         /* Check if the distance is within the distance where
985          * we use only the bounding box distance rbb,
986          * or within the cut-off and there is at least one atom pair
987          * within the cut-off.
988          */
989         if (d2 < rbb2)
990         {
991             InRange = TRUE;
992         }
993         else if (d2 < rlist2)
994         {
995             int cjf_gl = jGrid.cellOffset() + jclusterFirst;
996             for (int i = 0; i < c_nbnxnCpuIClusterSize && !InRange; i++)
997             {
998                 for (int j = 0; j < c_nbnxnCpuIClusterSize; j++)
999                 {
1000                     InRange =
1001                             InRange
1002                             || (gmx::square(x_ci[i * STRIDE_XYZ + XX]
1003                                             - x_j[(cjf_gl * c_nbnxnCpuIClusterSize + j) * STRIDE_XYZ + XX])
1004                                         + gmx::square(x_ci[i * STRIDE_XYZ + YY]
1005                                                       - x_j[(cjf_gl * c_nbnxnCpuIClusterSize + j) * STRIDE_XYZ + YY])
1006                                         + gmx::square(x_ci[i * STRIDE_XYZ + ZZ]
1007                                                       - x_j[(cjf_gl * c_nbnxnCpuIClusterSize + j) * STRIDE_XYZ + ZZ])
1008                                 < rlist2);
1009                 }
1010             }
1011             *numDistanceChecks += c_nbnxnCpuIClusterSize * c_nbnxnCpuIClusterSize;
1012         }
1013         if (!InRange)
1014         {
1015             jclusterFirst++;
1016         }
1017     }
1018     if (!InRange)
1019     {
1020         return;
1021     }
1022
1023     InRange = FALSE;
1024     while (!InRange && jclusterLast > jclusterFirst)
1025     {
1026         real d2 = clusterBoundingBoxDistance2(bb_ci[0], jGrid.jBoundingBoxes()[jclusterLast]);
1027         *numDistanceChecks += 2;
1028
1029         /* Check if the distance is within the distance where
1030          * we use only the bounding box distance rbb,
1031          * or within the cut-off and there is at least one atom pair
1032          * within the cut-off.
1033          */
1034         if (d2 < rbb2)
1035         {
1036             InRange = TRUE;
1037         }
1038         else if (d2 < rlist2)
1039         {
1040             int cjl_gl = jGrid.cellOffset() + jclusterLast;
1041             for (int i = 0; i < c_nbnxnCpuIClusterSize && !InRange; i++)
1042             {
1043                 for (int j = 0; j < c_nbnxnCpuIClusterSize; j++)
1044                 {
1045                     InRange =
1046                             InRange
1047                             || (gmx::square(x_ci[i * STRIDE_XYZ + XX]
1048                                             - x_j[(cjl_gl * c_nbnxnCpuIClusterSize + j) * STRIDE_XYZ + XX])
1049                                         + gmx::square(x_ci[i * STRIDE_XYZ + YY]
1050                                                       - x_j[(cjl_gl * c_nbnxnCpuIClusterSize + j) * STRIDE_XYZ + YY])
1051                                         + gmx::square(x_ci[i * STRIDE_XYZ + ZZ]
1052                                                       - x_j[(cjl_gl * c_nbnxnCpuIClusterSize + j) * STRIDE_XYZ + ZZ])
1053                                 < rlist2);
1054                 }
1055             }
1056             *numDistanceChecks += c_nbnxnCpuIClusterSize * c_nbnxnCpuIClusterSize;
1057         }
1058         if (!InRange)
1059         {
1060             jclusterLast--;
1061         }
1062     }
1063
1064     if (jclusterFirst <= jclusterLast)
1065     {
1066         for (int jcluster = jclusterFirst; jcluster <= jclusterLast; jcluster++)
1067         {
1068             /* Store cj and the interaction mask */
1069             nbnxn_cj_t cjEntry;
1070             cjEntry.cj   = jGrid.cellOffset() + jcluster;
1071             cjEntry.excl = get_imask(excludeSubDiagonal, icluster, jcluster);
1072             nbl->cj.push_back(cjEntry);
1073         }
1074         /* Increase the closing index in the i list */
1075         nbl->ci.back().cj_ind_end = nbl->cj.size();
1076     }
1077 }
1078
1079 #ifdef GMX_NBNXN_SIMD_4XN
1080 #    include "pairlist_simd_4xm.h"
1081 #endif
1082 #ifdef GMX_NBNXN_SIMD_2XNN
1083 #    include "pairlist_simd_2xmm.h"
1084 #endif
1085
1086 /* Plain C or SIMD4 code for making a pair list of super-cell sci vs scj.
1087  * Checks bounding box distances and possibly atom pair distances.
1088  */
1089 static void make_cluster_list_supersub(const Grid&       iGrid,
1090                                        const Grid&       jGrid,
1091                                        NbnxnPairlistGpu* nbl,
1092                                        const int         sci,
1093                                        const int         scj,
1094                                        const bool        excludeSubDiagonal,
1095                                        const int         stride,
1096                                        const real*       x,
1097                                        const real        rlist2,
1098                                        const float       rbb2,
1099                                        int*              numDistanceChecks)
1100 {
1101     NbnxnPairlistGpuWork& work = *nbl->work;
1102
1103 #if NBNXN_BBXXXX
1104     const float* pbb_ci = work.iSuperClusterData.bbPacked.data();
1105 #else
1106     const BoundingBox* bb_ci = work.iSuperClusterData.bb.data();
1107 #endif
1108
1109     assert(c_nbnxnGpuClusterSize == iGrid.geometry().numAtomsICluster);
1110     assert(c_nbnxnGpuClusterSize == jGrid.geometry().numAtomsICluster);
1111
1112     /* We generate the pairlist mainly based on bounding-box distances
1113      * and do atom pair distance based pruning on the GPU.
1114      * Only if a j-group contains a single cluster-pair, we try to prune
1115      * that pair based on atom distances on the CPU to avoid empty j-groups.
1116      */
1117 #define PRUNE_LIST_CPU_ONE 1
1118 #define PRUNE_LIST_CPU_ALL 0
1119
1120 #if PRUNE_LIST_CPU_ONE
1121     int ci_last = -1;
1122 #endif
1123
1124     float* d2l = work.distanceBuffer.data();
1125
1126     for (int subc = 0; subc < jGrid.numClustersPerCell()[scj]; subc++)
1127     {
1128         const int cj4_ind   = work.cj_ind / c_nbnxnGpuJgroupSize;
1129         const int cj_offset = work.cj_ind - cj4_ind * c_nbnxnGpuJgroupSize;
1130         const int cj        = scj * c_gpuNumClusterPerCell + subc;
1131
1132         const int cj_gl = jGrid.cellOffset() * c_gpuNumClusterPerCell + cj;
1133
1134         int ci1;
1135         if (excludeSubDiagonal && sci == scj)
1136         {
1137             ci1 = subc + 1;
1138         }
1139         else
1140         {
1141             ci1 = iGrid.numClustersPerCell()[sci];
1142         }
1143
1144 #if NBNXN_BBXXXX
1145         /* Determine all ci1 bb distances in one call with SIMD4 */
1146         const int offset = packedBoundingBoxesIndex(cj) + (cj & (c_packedBoundingBoxesDimSize - 1));
1147         clusterBoundingBoxDistance2_xxxx_simd4(jGrid.packedBoundingBoxes().data() + offset, ci1,
1148                                                pbb_ci, d2l);
1149         *numDistanceChecks += c_nbnxnGpuClusterSize * 2;
1150 #endif
1151
1152         int          npair = 0;
1153         unsigned int imask = 0;
1154         /* We use a fixed upper-bound instead of ci1 to help optimization */
1155         for (int ci = 0; ci < c_gpuNumClusterPerCell; ci++)
1156         {
1157             if (ci == ci1)
1158             {
1159                 break;
1160             }
1161
1162 #if !NBNXN_BBXXXX
1163             /* Determine the bb distance between ci and cj */
1164             d2l[ci] = clusterBoundingBoxDistance2(bb_ci[ci], jGrid.jBoundingBoxes()[cj]);
1165             *numDistanceChecks += 2;
1166 #endif
1167             float d2 = d2l[ci];
1168
1169 #if PRUNE_LIST_CPU_ALL
1170             /* Check if the distance is within the distance where
1171              * we use only the bounding box distance rbb,
1172              * or within the cut-off and there is at least one atom pair
1173              * within the cut-off. This check is very costly.
1174              */
1175             *numDistanceChecks += c_nbnxnGpuClusterSize * c_nbnxnGpuClusterSize;
1176             if (d2 < rbb2 || (d2 < rlist2 && clusterpair_in_range(work, ci, cj_gl, stride, x, rlist2)))
1177 #else
1178             /* Check if the distance between the two bounding boxes
1179              * in within the pair-list cut-off.
1180              */
1181             if (d2 < rlist2)
1182 #endif
1183             {
1184                 /* Flag this i-subcell to be taken into account */
1185                 imask |= (1U << (cj_offset * c_gpuNumClusterPerCell + ci));
1186
1187 #if PRUNE_LIST_CPU_ONE
1188                 ci_last = ci;
1189 #endif
1190
1191                 npair++;
1192             }
1193         }
1194
1195 #if PRUNE_LIST_CPU_ONE
1196         /* If we only found 1 pair, check if any atoms are actually
1197          * within the cut-off, so we could get rid of it.
1198          */
1199         if (npair == 1 && d2l[ci_last] >= rbb2
1200             && !clusterpair_in_range(work, ci_last, cj_gl, stride, x, rlist2))
1201         {
1202             imask &= ~(1U << (cj_offset * c_gpuNumClusterPerCell + ci_last));
1203             npair--;
1204         }
1205 #endif
1206
1207         if (npair > 0)
1208         {
1209             /* We have at least one cluster pair: add a j-entry */
1210             if (static_cast<size_t>(cj4_ind) == nbl->cj4.size())
1211             {
1212                 nbl->cj4.resize(nbl->cj4.size() + 1);
1213             }
1214             nbnxn_cj4_t* cj4 = &nbl->cj4[cj4_ind];
1215
1216             cj4->cj[cj_offset] = cj_gl;
1217
1218             /* Set the exclusions for the ci==sj entry.
1219              * Here we don't bother to check if this entry is actually flagged,
1220              * as it will nearly always be in the list.
1221              */
1222             if (excludeSubDiagonal && sci == scj)
1223             {
1224                 setSelfAndNewtonExclusionsGpu(nbl, cj4_ind, cj_offset, subc);
1225             }
1226
1227             /* Copy the cluster interaction mask to the list */
1228             for (int w = 0; w < c_nbnxnGpuClusterpairSplit; w++)
1229             {
1230                 cj4->imei[w].imask |= imask;
1231             }
1232
1233             nbl->work->cj_ind++;
1234
1235             /* Keep the count */
1236             nbl->nci_tot += npair;
1237
1238             /* Increase the closing index in i super-cell list */
1239             nbl->sci.back().cj4_ind_end =
1240                     (nbl->work->cj_ind + c_nbnxnGpuJgroupSize - 1) / c_nbnxnGpuJgroupSize;
1241         }
1242     }
1243 }
1244
1245 /* Returns how many contiguous j-clusters we have starting in the i-list */
1246 template<typename CjListType>
1247 static int numContiguousJClusters(const int                       cjIndexStart,
1248                                   const int                       cjIndexEnd,
1249                                   gmx::ArrayRef<const CjListType> cjList)
1250 {
1251     const int firstJCluster = nblCj(cjList, cjIndexStart);
1252
1253     int numContiguous = 0;
1254
1255     while (cjIndexStart + numContiguous < cjIndexEnd
1256            && nblCj(cjList, cjIndexStart + numContiguous) == firstJCluster + numContiguous)
1257     {
1258         numContiguous++;
1259     }
1260
1261     return numContiguous;
1262 }
1263
1264 /*! \internal
1265  * \brief Helper struct for efficient searching for excluded atoms in a j-list
1266  */
1267 struct JListRanges
1268 {
1269     /*! \brief Constructs a j-list range from \p cjList with the given index range */
1270     template<typename CjListType>
1271     JListRanges(int cjIndexStart, int cjIndexEnd, gmx::ArrayRef<const CjListType> cjList);
1272
1273     int cjIndexStart; //!< The start index in the j-list
1274     int cjIndexEnd;   //!< The end index in the j-list
1275     int cjFirst;      //!< The j-cluster with index cjIndexStart
1276     int cjLast;       //!< The j-cluster with index cjIndexEnd-1
1277     int numDirect; //!< Up to cjIndexStart+numDirect the j-clusters are cjFirst + the index offset
1278 };
1279
1280 #ifndef DOXYGEN
1281 template<typename CjListType>
1282 JListRanges::JListRanges(int cjIndexStart, int cjIndexEnd, gmx::ArrayRef<const CjListType> cjList) :
1283     cjIndexStart(cjIndexStart),
1284     cjIndexEnd(cjIndexEnd)
1285 {
1286     GMX_ASSERT(cjIndexEnd > cjIndexStart, "JListRanges should only be called with non-empty lists");
1287
1288     cjFirst = nblCj(cjList, cjIndexStart);
1289     cjLast  = nblCj(cjList, cjIndexEnd - 1);
1290
1291     /* Determine how many contiguous j-cells we have starting
1292      * from the first i-cell. This number can be used to directly
1293      * calculate j-cell indices for excluded atoms.
1294      */
1295     numDirect = numContiguousJClusters(cjIndexStart, cjIndexEnd, cjList);
1296 }
1297 #endif // !DOXYGEN
1298
1299 /* Return the index of \p jCluster in the given range or -1 when not present
1300  *
1301  * Note: This code is executed very often and therefore performance is
1302  *       important. It should be inlined and fully optimized.
1303  */
1304 template<typename CjListType>
1305 static inline int findJClusterInJList(int                             jCluster,
1306                                       const JListRanges&              ranges,
1307                                       gmx::ArrayRef<const CjListType> cjList)
1308 {
1309     int index;
1310
1311     if (jCluster < ranges.cjFirst + ranges.numDirect)
1312     {
1313         /* We can calculate the index directly using the offset */
1314         index = ranges.cjIndexStart + jCluster - ranges.cjFirst;
1315     }
1316     else
1317     {
1318         /* Search for jCluster using bisection */
1319         index          = -1;
1320         int rangeStart = ranges.cjIndexStart + ranges.numDirect;
1321         int rangeEnd   = ranges.cjIndexEnd;
1322         int rangeMiddle;
1323         while (index == -1 && rangeStart < rangeEnd)
1324         {
1325             rangeMiddle = (rangeStart + rangeEnd) >> 1;
1326
1327             const int clusterMiddle = nblCj(cjList, rangeMiddle);
1328
1329             if (jCluster == clusterMiddle)
1330             {
1331                 index = rangeMiddle;
1332             }
1333             else if (jCluster < clusterMiddle)
1334             {
1335                 rangeEnd = rangeMiddle;
1336             }
1337             else
1338             {
1339                 rangeStart = rangeMiddle + 1;
1340             }
1341         }
1342     }
1343
1344     return index;
1345 }
1346
1347 // TODO: Get rid of the two functions below by renaming sci to ci (or something better)
1348
1349 /* Return the i-entry in the list we are currently operating on */
1350 static nbnxn_ci_t* getOpenIEntry(NbnxnPairlistCpu* nbl)
1351 {
1352     return &nbl->ci.back();
1353 }
1354
1355 /* Return the i-entry in the list we are currently operating on */
1356 static nbnxn_sci_t* getOpenIEntry(NbnxnPairlistGpu* nbl)
1357 {
1358     return &nbl->sci.back();
1359 }
1360
1361 /* Set all atom-pair exclusions for a simple type list i-entry
1362  *
1363  * Set all atom-pair exclusions from the topology stored in exclusions
1364  * as masks in the pair-list for simple list entry iEntry.
1365  */
1366 static void setExclusionsForIEntry(const Nbnxm::GridSet& gridSet,
1367                                    NbnxnPairlistCpu*     nbl,
1368                                    gmx_bool              diagRemoved,
1369                                    int                   na_cj_2log,
1370                                    const nbnxn_ci_t&     iEntry,
1371                                    const t_blocka&       exclusions)
1372 {
1373     if (iEntry.cj_ind_end == iEntry.cj_ind_start)
1374     {
1375         /* Empty list: no exclusions */
1376         return;
1377     }
1378
1379     const JListRanges ranges(iEntry.cj_ind_start, iEntry.cj_ind_end, gmx::makeConstArrayRef(nbl->cj));
1380
1381     const int iCluster = iEntry.ci;
1382
1383     gmx::ArrayRef<const int> cell        = gridSet.cells();
1384     gmx::ArrayRef<const int> atomIndices = gridSet.atomIndices();
1385
1386     /* Loop over the atoms in the i-cluster */
1387     for (int i = 0; i < nbl->na_ci; i++)
1388     {
1389         const int iIndex = iCluster * nbl->na_ci + i;
1390         const int iAtom  = atomIndices[iIndex];
1391         if (iAtom >= 0)
1392         {
1393             /* Loop over the topology-based exclusions for this i-atom */
1394             for (int exclIndex = exclusions.index[iAtom]; exclIndex < exclusions.index[iAtom + 1];
1395                  exclIndex++)
1396             {
1397                 const int jAtom = exclusions.a[exclIndex];
1398
1399                 if (jAtom == iAtom)
1400                 {
1401                     /* The self exclusion are already set, save some time */
1402                     continue;
1403                 }
1404
1405                 /* Get the index of the j-atom in the nbnxn atom data */
1406                 const int jIndex = cell[jAtom];
1407
1408                 /* Without shifts we only calculate interactions j>i
1409                  * for one-way pair-lists.
1410                  */
1411                 if (diagRemoved && jIndex <= iIndex)
1412                 {
1413                     continue;
1414                 }
1415
1416                 const int jCluster = (jIndex >> na_cj_2log);
1417
1418                 /* Could the cluster se be in our list? */
1419                 if (jCluster >= ranges.cjFirst && jCluster <= ranges.cjLast)
1420                 {
1421                     const int index =
1422                             findJClusterInJList(jCluster, ranges, gmx::makeConstArrayRef(nbl->cj));
1423
1424                     if (index >= 0)
1425                     {
1426                         /* We found an exclusion, clear the corresponding
1427                          * interaction bit.
1428                          */
1429                         const int innerJ = jIndex - (jCluster << na_cj_2log);
1430
1431                         nbl->cj[index].excl &= ~(1U << ((i << na_cj_2log) + innerJ));
1432                     }
1433                 }
1434             }
1435         }
1436     }
1437 }
1438
1439 /* Add a new i-entry to the FEP list and copy the i-properties */
1440 static inline void fep_list_new_nri_copy(t_nblist* nlist)
1441 {
1442     /* Add a new i-entry */
1443     nlist->nri++;
1444
1445     assert(nlist->nri < nlist->maxnri);
1446
1447     /* Duplicate the last i-entry, except for jindex, which continues */
1448     nlist->iinr[nlist->nri]   = nlist->iinr[nlist->nri - 1];
1449     nlist->shift[nlist->nri]  = nlist->shift[nlist->nri - 1];
1450     nlist->gid[nlist->nri]    = nlist->gid[nlist->nri - 1];
1451     nlist->jindex[nlist->nri] = nlist->nrj;
1452 }
1453
1454 /* Rellocate FEP list for size nl->maxnri, TODO: replace by C++ */
1455 static void reallocate_nblist(t_nblist* nl)
1456 {
1457     if (gmx_debug_at)
1458     {
1459         fprintf(debug,
1460                 "reallocating neigborlist (ielec=%d, ivdw=%d, igeometry=%d, type=%d), maxnri=%d\n",
1461                 nl->ielec, nl->ivdw, nl->igeometry, nl->type, nl->maxnri);
1462     }
1463     srenew(nl->iinr, nl->maxnri);
1464     srenew(nl->gid, nl->maxnri);
1465     srenew(nl->shift, nl->maxnri);
1466     srenew(nl->jindex, nl->maxnri + 1);
1467 }
1468
1469 /* For load balancing of the free-energy lists over threads, we set
1470  * the maximum nrj size of an i-entry to 40. This leads to good
1471  * load balancing in the worst case scenario of a single perturbed
1472  * particle on 16 threads, while not introducing significant overhead.
1473  * Note that half of the perturbed pairs will anyhow end up in very small lists,
1474  * since non perturbed i-particles will see few perturbed j-particles).
1475  */
1476 const int max_nrj_fep = 40;
1477
1478 /* Exclude the perturbed pairs from the Verlet list. This is only done to avoid
1479  * singularities for overlapping particles (0/0), since the charges and
1480  * LJ parameters have been zeroed in the nbnxn data structure.
1481  * Simultaneously make a group pair list for the perturbed pairs.
1482  */
1483 static void make_fep_list(gmx::ArrayRef<const int> atomIndices,
1484                           const nbnxn_atomdata_t*  nbat,
1485                           NbnxnPairlistCpu*        nbl,
1486                           gmx_bool                 bDiagRemoved,
1487                           nbnxn_ci_t*              nbl_ci,
1488                           real gmx_unused shx,
1489                           real gmx_unused shy,
1490                           real gmx_unused shz,
1491                           real gmx_unused rlist_fep2,
1492                           const Grid&     iGrid,
1493                           const Grid&     jGrid,
1494                           t_nblist*       nlist)
1495 {
1496     int      ci, cj_ind_start, cj_ind_end, cja, cjr;
1497     int      nri_max;
1498     int      gid_i = 0, gid_j, gid;
1499     int      egp_shift, egp_mask;
1500     int      gid_cj = 0;
1501     int      ind_i, ind_j, ai, aj;
1502     int      nri;
1503     gmx_bool bFEP_i, bFEP_i_all;
1504
1505     if (nbl_ci->cj_ind_end == nbl_ci->cj_ind_start)
1506     {
1507         /* Empty list */
1508         return;
1509     }
1510
1511     ci = nbl_ci->ci;
1512
1513     cj_ind_start = nbl_ci->cj_ind_start;
1514     cj_ind_end   = nbl_ci->cj_ind_end;
1515
1516     /* In worst case we have alternating energy groups
1517      * and create #atom-pair lists, which means we need the size
1518      * of a cluster pair (na_ci*na_cj) times the number of cj's.
1519      */
1520     nri_max = nbl->na_ci * nbl->na_cj * (cj_ind_end - cj_ind_start);
1521     if (nlist->nri + nri_max > nlist->maxnri)
1522     {
1523         nlist->maxnri = over_alloc_large(nlist->nri + nri_max);
1524         reallocate_nblist(nlist);
1525     }
1526
1527     const int numAtomsJCluster = jGrid.geometry().numAtomsJCluster;
1528
1529     const nbnxn_atomdata_t::Params& nbatParams = nbat->params();
1530
1531     const int ngid = nbatParams.nenergrp;
1532
1533     /* TODO: Consider adding a check in grompp and changing this to an assert */
1534     const int numBitsInEnergyGroupIdsForAtomsInJCluster = sizeof(gid_cj) * 8;
1535     if (ngid * numAtomsJCluster > numBitsInEnergyGroupIdsForAtomsInJCluster)
1536     {
1537         gmx_fatal(FARGS,
1538                   "The Verlet scheme with %dx%d kernels and free-energy only supports up to %zu "
1539                   "energy groups",
1540                   iGrid.geometry().numAtomsICluster, numAtomsJCluster,
1541                   (sizeof(gid_cj) * 8) / numAtomsJCluster);
1542     }
1543
1544     egp_shift = nbatParams.neg_2log;
1545     egp_mask  = (1 << egp_shift) - 1;
1546
1547     /* Loop over the atoms in the i sub-cell */
1548     bFEP_i_all = TRUE;
1549     for (int i = 0; i < nbl->na_ci; i++)
1550     {
1551         ind_i = ci * nbl->na_ci + i;
1552         ai    = atomIndices[ind_i];
1553         if (ai >= 0)
1554         {
1555             nri                    = nlist->nri;
1556             nlist->jindex[nri + 1] = nlist->jindex[nri];
1557             nlist->iinr[nri]       = ai;
1558             /* The actual energy group pair index is set later */
1559             nlist->gid[nri]   = 0;
1560             nlist->shift[nri] = nbl_ci->shift & NBNXN_CI_SHIFT;
1561
1562             bFEP_i = iGrid.atomIsPerturbed(ci - iGrid.cellOffset(), i);
1563
1564             bFEP_i_all = bFEP_i_all && bFEP_i;
1565
1566             if (nlist->nrj + (cj_ind_end - cj_ind_start) * nbl->na_cj > nlist->maxnrj)
1567             {
1568                 nlist->maxnrj = over_alloc_small(nlist->nrj + (cj_ind_end - cj_ind_start) * nbl->na_cj);
1569                 srenew(nlist->jjnr, nlist->maxnrj);
1570                 srenew(nlist->excl_fep, nlist->maxnrj);
1571             }
1572
1573             if (ngid > 1)
1574             {
1575                 gid_i = (nbatParams.energrp[ci] >> (egp_shift * i)) & egp_mask;
1576             }
1577
1578             for (int cj_ind = cj_ind_start; cj_ind < cj_ind_end; cj_ind++)
1579             {
1580                 unsigned int fep_cj;
1581
1582                 cja = nbl->cj[cj_ind].cj;
1583
1584                 if (numAtomsJCluster == jGrid.geometry().numAtomsICluster)
1585                 {
1586                     cjr    = cja - jGrid.cellOffset();
1587                     fep_cj = jGrid.fepBits(cjr);
1588                     if (ngid > 1)
1589                     {
1590                         gid_cj = nbatParams.energrp[cja];
1591                     }
1592                 }
1593                 else if (2 * numAtomsJCluster == jGrid.geometry().numAtomsICluster)
1594                 {
1595                     cjr = cja - jGrid.cellOffset() * 2;
1596                     /* Extract half of the ci fep/energrp mask */
1597                     fep_cj = (jGrid.fepBits(cjr >> 1) >> ((cjr & 1) * numAtomsJCluster))
1598                              & ((1 << numAtomsJCluster) - 1);
1599                     if (ngid > 1)
1600                     {
1601                         gid_cj = nbatParams.energrp[cja >> 1] >> ((cja & 1) * numAtomsJCluster * egp_shift)
1602                                  & ((1 << (numAtomsJCluster * egp_shift)) - 1);
1603                     }
1604                 }
1605                 else
1606                 {
1607                     cjr = cja - (jGrid.cellOffset() >> 1);
1608                     /* Combine two ci fep masks/energrp */
1609                     fep_cj = jGrid.fepBits(cjr * 2)
1610                              + (jGrid.fepBits(cjr * 2 + 1) << jGrid.geometry().numAtomsICluster);
1611                     if (ngid > 1)
1612                     {
1613                         gid_cj = nbatParams.energrp[cja * 2]
1614                                  + (nbatParams.energrp[cja * 2 + 1]
1615                                     << (jGrid.geometry().numAtomsICluster * egp_shift));
1616                     }
1617                 }
1618
1619                 if (bFEP_i || fep_cj != 0)
1620                 {
1621                     for (int j = 0; j < nbl->na_cj; j++)
1622                     {
1623                         /* Is this interaction perturbed and not excluded? */
1624                         ind_j = cja * nbl->na_cj + j;
1625                         aj    = atomIndices[ind_j];
1626                         if (aj >= 0 && (bFEP_i || (fep_cj & (1 << j))) && (!bDiagRemoved || ind_j >= ind_i))
1627                         {
1628                             if (ngid > 1)
1629                             {
1630                                 gid_j = (gid_cj >> (j * egp_shift)) & egp_mask;
1631                                 gid   = GID(gid_i, gid_j, ngid);
1632
1633                                 if (nlist->nrj > nlist->jindex[nri] && nlist->gid[nri] != gid)
1634                                 {
1635                                     /* Energy group pair changed: new list */
1636                                     fep_list_new_nri_copy(nlist);
1637                                     nri = nlist->nri;
1638                                 }
1639                                 nlist->gid[nri] = gid;
1640                             }
1641
1642                             if (nlist->nrj - nlist->jindex[nri] >= max_nrj_fep)
1643                             {
1644                                 fep_list_new_nri_copy(nlist);
1645                                 nri = nlist->nri;
1646                             }
1647
1648                             /* Add it to the FEP list */
1649                             nlist->jjnr[nlist->nrj] = aj;
1650                             nlist->excl_fep[nlist->nrj] =
1651                                     (nbl->cj[cj_ind].excl >> (i * nbl->na_cj + j)) & 1;
1652                             nlist->nrj++;
1653
1654                             /* Exclude it from the normal list.
1655                              * Note that the charge has been set to zero,
1656                              * but we need to avoid 0/0, as perturbed atoms
1657                              * can be on top of each other.
1658                              */
1659                             nbl->cj[cj_ind].excl &= ~(1U << (i * nbl->na_cj + j));
1660                         }
1661                     }
1662                 }
1663             }
1664
1665             if (nlist->nrj > nlist->jindex[nri])
1666             {
1667                 /* Actually add this new, non-empty, list */
1668                 nlist->nri++;
1669                 nlist->jindex[nlist->nri] = nlist->nrj;
1670             }
1671         }
1672     }
1673
1674     if (bFEP_i_all)
1675     {
1676         /* All interactions are perturbed, we can skip this entry */
1677         nbl_ci->cj_ind_end = cj_ind_start;
1678         nbl->ncjInUse -= cj_ind_end - cj_ind_start;
1679     }
1680 }
1681
1682 /* Return the index of atom a within a cluster */
1683 static inline int cj_mod_cj4(int cj)
1684 {
1685     return cj & (c_nbnxnGpuJgroupSize - 1);
1686 }
1687
1688 /* Convert a j-cluster to a cj4 group */
1689 static inline int cj_to_cj4(int cj)
1690 {
1691     return cj / c_nbnxnGpuJgroupSize;
1692 }
1693
1694 /* Return the index of an j-atom within a warp */
1695 static inline int a_mod_wj(int a)
1696 {
1697     return a & (c_nbnxnGpuClusterSize / c_nbnxnGpuClusterpairSplit - 1);
1698 }
1699
1700 /* As make_fep_list above, but for super/sub lists. */
1701 static void make_fep_list(gmx::ArrayRef<const int> atomIndices,
1702                           const nbnxn_atomdata_t*  nbat,
1703                           NbnxnPairlistGpu*        nbl,
1704                           gmx_bool                 bDiagRemoved,
1705                           const nbnxn_sci_t*       nbl_sci,
1706                           real                     shx,
1707                           real                     shy,
1708                           real                     shz,
1709                           real                     rlist_fep2,
1710                           const Grid&              iGrid,
1711                           const Grid&              jGrid,
1712                           t_nblist*                nlist)
1713 {
1714     int                nri_max;
1715     int                c_abs;
1716     int                ind_i, ind_j, ai, aj;
1717     int                nri;
1718     gmx_bool           bFEP_i;
1719     real               xi, yi, zi;
1720     const nbnxn_cj4_t* cj4;
1721
1722     const int numJClusterGroups = nbl_sci->numJClusterGroups();
1723     if (numJClusterGroups == 0)
1724     {
1725         /* Empty list */
1726         return;
1727     }
1728
1729     const int sci = nbl_sci->sci;
1730
1731     const int cj4_ind_start = nbl_sci->cj4_ind_start;
1732     const int cj4_ind_end   = nbl_sci->cj4_ind_end;
1733
1734     /* Here we process one super-cell, max #atoms na_sc, versus a list
1735      * cj4 entries, each with max c_nbnxnGpuJgroupSize cj's, each
1736      * of size na_cj atoms.
1737      * On the GPU we don't support energy groups (yet).
1738      * So for each of the na_sc i-atoms, we need max one FEP list
1739      * for each max_nrj_fep j-atoms.
1740      */
1741     nri_max = nbl->na_sc * nbl->na_cj * (1 + (numJClusterGroups * c_nbnxnGpuJgroupSize) / max_nrj_fep);
1742     if (nlist->nri + nri_max > nlist->maxnri)
1743     {
1744         nlist->maxnri = over_alloc_large(nlist->nri + nri_max);
1745         reallocate_nblist(nlist);
1746     }
1747
1748     /* Loop over the atoms in the i super-cluster */
1749     for (int c = 0; c < c_gpuNumClusterPerCell; c++)
1750     {
1751         c_abs = sci * c_gpuNumClusterPerCell + c;
1752
1753         for (int i = 0; i < nbl->na_ci; i++)
1754         {
1755             ind_i = c_abs * nbl->na_ci + i;
1756             ai    = atomIndices[ind_i];
1757             if (ai >= 0)
1758             {
1759                 nri                    = nlist->nri;
1760                 nlist->jindex[nri + 1] = nlist->jindex[nri];
1761                 nlist->iinr[nri]       = ai;
1762                 /* With GPUs, energy groups are not supported */
1763                 nlist->gid[nri]   = 0;
1764                 nlist->shift[nri] = nbl_sci->shift & NBNXN_CI_SHIFT;
1765
1766                 bFEP_i = iGrid.atomIsPerturbed(c_abs - iGrid.cellOffset() * c_gpuNumClusterPerCell, i);
1767
1768                 xi = nbat->x()[ind_i * nbat->xstride + XX] + shx;
1769                 yi = nbat->x()[ind_i * nbat->xstride + YY] + shy;
1770                 zi = nbat->x()[ind_i * nbat->xstride + ZZ] + shz;
1771
1772                 const int nrjMax = nlist->nrj + numJClusterGroups * c_nbnxnGpuJgroupSize * nbl->na_cj;
1773                 if (nrjMax > nlist->maxnrj)
1774                 {
1775                     nlist->maxnrj = over_alloc_small(nrjMax);
1776                     srenew(nlist->jjnr, nlist->maxnrj);
1777                     srenew(nlist->excl_fep, nlist->maxnrj);
1778                 }
1779
1780                 for (int cj4_ind = cj4_ind_start; cj4_ind < cj4_ind_end; cj4_ind++)
1781                 {
1782                     cj4 = &nbl->cj4[cj4_ind];
1783
1784                     for (int gcj = 0; gcj < c_nbnxnGpuJgroupSize; gcj++)
1785                     {
1786                         if ((cj4->imei[0].imask & (1U << (gcj * c_gpuNumClusterPerCell + c))) == 0)
1787                         {
1788                             /* Skip this ci for this cj */
1789                             continue;
1790                         }
1791
1792                         const int cjr = cj4->cj[gcj] - jGrid.cellOffset() * c_gpuNumClusterPerCell;
1793
1794                         if (bFEP_i || jGrid.clusterIsPerturbed(cjr))
1795                         {
1796                             for (int j = 0; j < nbl->na_cj; j++)
1797                             {
1798                                 /* Is this interaction perturbed and not excluded? */
1799                                 ind_j = (jGrid.cellOffset() * c_gpuNumClusterPerCell + cjr) * nbl->na_cj + j;
1800                                 aj = atomIndices[ind_j];
1801                                 if (aj >= 0 && (bFEP_i || jGrid.atomIsPerturbed(cjr, j))
1802                                     && (!bDiagRemoved || ind_j >= ind_i))
1803                                 {
1804                                     int          excl_pair;
1805                                     unsigned int excl_bit;
1806                                     real         dx, dy, dz;
1807
1808                                     const int jHalf =
1809                                             j / (c_nbnxnGpuClusterSize / c_nbnxnGpuClusterpairSplit);
1810                                     nbnxn_excl_t& excl = get_exclusion_mask(nbl, cj4_ind, jHalf);
1811
1812                                     excl_pair = a_mod_wj(j) * nbl->na_ci + i;
1813                                     excl_bit  = (1U << (gcj * c_gpuNumClusterPerCell + c));
1814
1815                                     dx = nbat->x()[ind_j * nbat->xstride + XX] - xi;
1816                                     dy = nbat->x()[ind_j * nbat->xstride + YY] - yi;
1817                                     dz = nbat->x()[ind_j * nbat->xstride + ZZ] - zi;
1818
1819                                     /* The unpruned GPU list has more than 2/3
1820                                      * of the atom pairs beyond rlist. Using
1821                                      * this list will cause a lot of overhead
1822                                      * in the CPU FEP kernels, especially
1823                                      * relative to the fast GPU kernels.
1824                                      * So we prune the FEP list here.
1825                                      */
1826                                     if (dx * dx + dy * dy + dz * dz < rlist_fep2)
1827                                     {
1828                                         if (nlist->nrj - nlist->jindex[nri] >= max_nrj_fep)
1829                                         {
1830                                             fep_list_new_nri_copy(nlist);
1831                                             nri = nlist->nri;
1832                                         }
1833
1834                                         /* Add it to the FEP list */
1835                                         nlist->jjnr[nlist->nrj] = aj;
1836                                         nlist->excl_fep[nlist->nrj] =
1837                                                 (excl.pair[excl_pair] & excl_bit) ? 1 : 0;
1838                                         nlist->nrj++;
1839                                     }
1840
1841                                     /* Exclude it from the normal list.
1842                                      * Note that the charge and LJ parameters have
1843                                      * been set to zero, but we need to avoid 0/0,
1844                                      * as perturbed atoms can be on top of each other.
1845                                      */
1846                                     excl.pair[excl_pair] &= ~excl_bit;
1847                                 }
1848                             }
1849
1850                             /* Note that we could mask out this pair in imask
1851                              * if all i- and/or all j-particles are perturbed.
1852                              * But since the perturbed pairs on the CPU will
1853                              * take an order of magnitude more time, the GPU
1854                              * will finish before the CPU and there is no gain.
1855                              */
1856                         }
1857                     }
1858                 }
1859
1860                 if (nlist->nrj > nlist->jindex[nri])
1861                 {
1862                     /* Actually add this new, non-empty, list */
1863                     nlist->nri++;
1864                     nlist->jindex[nlist->nri] = nlist->nrj;
1865                 }
1866             }
1867         }
1868     }
1869 }
1870
1871 /* Set all atom-pair exclusions for a GPU type list i-entry
1872  *
1873  * Sets all atom-pair exclusions from the topology stored in exclusions
1874  * as masks in the pair-list for i-super-cluster list entry iEntry.
1875  */
1876 static void setExclusionsForIEntry(const Nbnxm::GridSet& gridSet,
1877                                    NbnxnPairlistGpu*     nbl,
1878                                    gmx_bool              diagRemoved,
1879                                    int gmx_unused     na_cj_2log,
1880                                    const nbnxn_sci_t& iEntry,
1881                                    const t_blocka&    exclusions)
1882 {
1883     if (iEntry.numJClusterGroups() == 0)
1884     {
1885         /* Empty list */
1886         return;
1887     }
1888
1889     /* Set the search ranges using start and end j-cluster indices.
1890      * Note that here we can not use cj4_ind_end, since the last cj4
1891      * can be only partially filled, so we use cj_ind.
1892      */
1893     const JListRanges ranges(iEntry.cj4_ind_start * c_nbnxnGpuJgroupSize, nbl->work->cj_ind,
1894                              gmx::makeConstArrayRef(nbl->cj4));
1895
1896     GMX_ASSERT(nbl->na_ci == c_nbnxnGpuClusterSize, "na_ci should match the GPU cluster size");
1897     constexpr int c_clusterSize      = c_nbnxnGpuClusterSize;
1898     constexpr int c_superClusterSize = c_nbnxnGpuNumClusterPerSupercluster * c_nbnxnGpuClusterSize;
1899
1900     const int iSuperCluster = iEntry.sci;
1901
1902     gmx::ArrayRef<const int> atomIndices = gridSet.atomIndices();
1903     gmx::ArrayRef<const int> cell        = gridSet.cells();
1904
1905     /* Loop over the atoms in the i super-cluster */
1906     for (int i = 0; i < c_superClusterSize; i++)
1907     {
1908         const int iIndex = iSuperCluster * c_superClusterSize + i;
1909         const int iAtom  = atomIndices[iIndex];
1910         if (iAtom >= 0)
1911         {
1912             const int iCluster = i / c_clusterSize;
1913
1914             /* Loop over the topology-based exclusions for this i-atom */
1915             for (int exclIndex = exclusions.index[iAtom]; exclIndex < exclusions.index[iAtom + 1];
1916                  exclIndex++)
1917             {
1918                 const int jAtom = exclusions.a[exclIndex];
1919
1920                 if (jAtom == iAtom)
1921                 {
1922                     /* The self exclusions are already set, save some time */
1923                     continue;
1924                 }
1925
1926                 /* Get the index of the j-atom in the nbnxn atom data */
1927                 const int jIndex = cell[jAtom];
1928
1929                 /* Without shifts we only calculate interactions j>i
1930                  * for one-way pair-lists.
1931                  */
1932                 /* NOTE: We would like to use iIndex on the right hand side,
1933                  * but that makes this routine 25% slower with gcc6/7.
1934                  * Even using c_superClusterSize makes it slower.
1935                  * Either of these changes triggers peeling of the exclIndex
1936                  * loop, which apparently leads to far less efficient code.
1937                  */
1938                 if (diagRemoved && jIndex <= iSuperCluster * nbl->na_sc + i)
1939                 {
1940                     continue;
1941                 }
1942
1943                 const int jCluster = jIndex / c_clusterSize;
1944
1945                 /* Check whether the cluster is in our list? */
1946                 if (jCluster >= ranges.cjFirst && jCluster <= ranges.cjLast)
1947                 {
1948                     const int index =
1949                             findJClusterInJList(jCluster, ranges, gmx::makeConstArrayRef(nbl->cj4));
1950
1951                     if (index >= 0)
1952                     {
1953                         /* We found an exclusion, clear the corresponding
1954                          * interaction bit.
1955                          */
1956                         const unsigned int pairMask =
1957                                 (1U << (cj_mod_cj4(index) * c_gpuNumClusterPerCell + iCluster));
1958                         /* Check if the i-cluster interacts with the j-cluster */
1959                         if (nbl_imask0(nbl, index) & pairMask)
1960                         {
1961                             const int innerI = (i & (c_clusterSize - 1));
1962                             const int innerJ = (jIndex & (c_clusterSize - 1));
1963
1964                             /* Determine which j-half (CUDA warp) we are in */
1965                             const int jHalf = innerJ / (c_clusterSize / c_nbnxnGpuClusterpairSplit);
1966
1967                             nbnxn_excl_t& interactionMask =
1968                                     get_exclusion_mask(nbl, cj_to_cj4(index), jHalf);
1969
1970                             interactionMask.pair[a_mod_wj(innerJ) * c_clusterSize + innerI] &= ~pairMask;
1971                         }
1972                     }
1973                 }
1974             }
1975         }
1976     }
1977 }
1978
1979 /* Make a new ci entry at the back of nbl->ci */
1980 static void addNewIEntry(NbnxnPairlistCpu* nbl, int ci, int shift, int flags)
1981 {
1982     nbnxn_ci_t ciEntry;
1983     ciEntry.ci    = ci;
1984     ciEntry.shift = shift;
1985     /* Store the interaction flags along with the shift */
1986     ciEntry.shift |= flags;
1987     ciEntry.cj_ind_start = nbl->cj.size();
1988     ciEntry.cj_ind_end   = nbl->cj.size();
1989     nbl->ci.push_back(ciEntry);
1990 }
1991
1992 /* Make a new sci entry at index nbl->nsci */
1993 static void addNewIEntry(NbnxnPairlistGpu* nbl, int sci, int shift, int gmx_unused flags)
1994 {
1995     nbnxn_sci_t sciEntry;
1996     sciEntry.sci           = sci;
1997     sciEntry.shift         = shift;
1998     sciEntry.cj4_ind_start = nbl->cj4.size();
1999     sciEntry.cj4_ind_end   = nbl->cj4.size();
2000
2001     nbl->sci.push_back(sciEntry);
2002 }
2003
2004 /* Sort the simple j-list cj on exclusions.
2005  * Entries with exclusions will all be sorted to the beginning of the list.
2006  */
2007 static void sort_cj_excl(nbnxn_cj_t* cj, int ncj, NbnxnPairlistCpuWork* work)
2008 {
2009     work->cj.resize(ncj);
2010
2011     /* Make a list of the j-cells involving exclusions */
2012     int jnew = 0;
2013     for (int j = 0; j < ncj; j++)
2014     {
2015         if (cj[j].excl != NBNXN_INTERACTION_MASK_ALL)
2016         {
2017             work->cj[jnew++] = cj[j];
2018         }
2019     }
2020     /* Check if there are exclusions at all or not just the first entry */
2021     if (!((jnew == 0) || (jnew == 1 && cj[0].excl != NBNXN_INTERACTION_MASK_ALL)))
2022     {
2023         for (int j = 0; j < ncj; j++)
2024         {
2025             if (cj[j].excl == NBNXN_INTERACTION_MASK_ALL)
2026             {
2027                 work->cj[jnew++] = cj[j];
2028             }
2029         }
2030         for (int j = 0; j < ncj; j++)
2031         {
2032             cj[j] = work->cj[j];
2033         }
2034     }
2035 }
2036
2037 /* Close this simple list i entry */
2038 static void closeIEntry(NbnxnPairlistCpu* nbl,
2039                         int gmx_unused sp_max_av,
2040                         gmx_bool gmx_unused progBal,
2041                         float gmx_unused nsp_tot_est,
2042                         int gmx_unused thread,
2043                         int gmx_unused nthread)
2044 {
2045     nbnxn_ci_t& ciEntry = nbl->ci.back();
2046
2047     /* All content of the new ci entry have already been filled correctly,
2048      * we only need to sort and increase counts or remove the entry when empty.
2049      */
2050     const int jlen = ciEntry.cj_ind_end - ciEntry.cj_ind_start;
2051     if (jlen > 0)
2052     {
2053         sort_cj_excl(nbl->cj.data() + ciEntry.cj_ind_start, jlen, nbl->work.get());
2054
2055         /* The counts below are used for non-bonded pair/flop counts
2056          * and should therefore match the available kernel setups.
2057          */
2058         if (!(ciEntry.shift & NBNXN_CI_DO_COUL(0)))
2059         {
2060             nbl->work->ncj_noq += jlen;
2061         }
2062         else if ((ciEntry.shift & NBNXN_CI_HALF_LJ(0)) || !(ciEntry.shift & NBNXN_CI_DO_LJ(0)))
2063         {
2064             nbl->work->ncj_hlj += jlen;
2065         }
2066     }
2067     else
2068     {
2069         /* Entry is empty: remove it  */
2070         nbl->ci.pop_back();
2071     }
2072 }
2073
2074 /* Split sci entry for load balancing on the GPU.
2075  * Splitting ensures we have enough lists to fully utilize the whole GPU.
2076  * With progBal we generate progressively smaller lists, which improves
2077  * load balancing. As we only know the current count on our own thread,
2078  * we will need to estimate the current total amount of i-entries.
2079  * As the lists get concatenated later, this estimate depends
2080  * both on nthread and our own thread index.
2081  */
2082 static void split_sci_entry(NbnxnPairlistGpu* nbl,
2083                             int               nsp_target_av,
2084                             gmx_bool          progBal,
2085                             float             nsp_tot_est,
2086                             int               thread,
2087                             int               nthread)
2088 {
2089     int nsp_max;
2090
2091     if (progBal)
2092     {
2093         float nsp_est;
2094
2095         /* Estimate the total numbers of ci's of the nblist combined
2096          * over all threads using the target number of ci's.
2097          */
2098         nsp_est = (nsp_tot_est * thread) / nthread + nbl->nci_tot;
2099
2100         /* The first ci blocks should be larger, to avoid overhead.
2101          * The last ci blocks should be smaller, to improve load balancing.
2102          * The factor 3/2 makes the first block 3/2 times the target average
2103          * and ensures that the total number of blocks end up equal to
2104          * that of equally sized blocks of size nsp_target_av.
2105          */
2106         nsp_max = static_cast<int>(nsp_target_av * (nsp_tot_est * 1.5 / (nsp_est + nsp_tot_est)));
2107     }
2108     else
2109     {
2110         nsp_max = nsp_target_av;
2111     }
2112
2113     const int cj4_start = nbl->sci.back().cj4_ind_start;
2114     const int cj4_end   = nbl->sci.back().cj4_ind_end;
2115     const int j4len     = cj4_end - cj4_start;
2116
2117     if (j4len > 1 && j4len * c_gpuNumClusterPerCell * c_nbnxnGpuJgroupSize > nsp_max)
2118     {
2119         /* Modify the last ci entry and process the cj4's again */
2120
2121         int nsp       = 0;
2122         int nsp_sci   = 0;
2123         int nsp_cj4_e = 0;
2124         int nsp_cj4   = 0;
2125         for (int cj4 = cj4_start; cj4 < cj4_end; cj4++)
2126         {
2127             int nsp_cj4_p = nsp_cj4;
2128             /* Count the number of cluster pairs in this cj4 group */
2129             nsp_cj4 = 0;
2130             for (int p = 0; p < c_gpuNumClusterPerCell * c_nbnxnGpuJgroupSize; p++)
2131             {
2132                 nsp_cj4 += (nbl->cj4[cj4].imei[0].imask >> p) & 1;
2133             }
2134
2135             /* If adding the current cj4 with nsp_cj4 pairs get us further
2136              * away from our target nsp_max, split the list before this cj4.
2137              */
2138             if (nsp > 0 && nsp_max - nsp < nsp + nsp_cj4 - nsp_max)
2139             {
2140                 /* Split the list at cj4 */
2141                 nbl->sci.back().cj4_ind_end = cj4;
2142                 /* Create a new sci entry */
2143                 nbnxn_sci_t sciNew;
2144                 sciNew.sci           = nbl->sci.back().sci;
2145                 sciNew.shift         = nbl->sci.back().shift;
2146                 sciNew.cj4_ind_start = cj4;
2147                 nbl->sci.push_back(sciNew);
2148
2149                 nsp_sci   = nsp;
2150                 nsp_cj4_e = nsp_cj4_p;
2151                 nsp       = 0;
2152             }
2153             nsp += nsp_cj4;
2154         }
2155
2156         /* Put the remaining cj4's in the last sci entry */
2157         nbl->sci.back().cj4_ind_end = cj4_end;
2158
2159         /* Possibly balance out the last two sci's
2160          * by moving the last cj4 of the second last sci.
2161          */
2162         if (nsp_sci - nsp_cj4_e >= nsp + nsp_cj4_e)
2163         {
2164             GMX_ASSERT(nbl->sci.size() >= 2, "We expect at least two elements");
2165             nbl->sci[nbl->sci.size() - 2].cj4_ind_end--;
2166             nbl->sci[nbl->sci.size() - 1].cj4_ind_start--;
2167         }
2168     }
2169 }
2170
2171 /* Clost this super/sub list i entry */
2172 static void closeIEntry(NbnxnPairlistGpu* nbl, int nsp_max_av, gmx_bool progBal, float nsp_tot_est, int thread, int nthread)
2173 {
2174     nbnxn_sci_t& sciEntry = *getOpenIEntry(nbl);
2175
2176     /* All content of the new ci entry have already been filled correctly,
2177      * we only need to, potentially, split or remove the entry when empty.
2178      */
2179     int j4len = sciEntry.numJClusterGroups();
2180     if (j4len > 0)
2181     {
2182         /* We can only have complete blocks of 4 j-entries in a list,
2183          * so round the count up before closing.
2184          */
2185         int ncj4          = (nbl->work->cj_ind + c_nbnxnGpuJgroupSize - 1) / c_nbnxnGpuJgroupSize;
2186         nbl->work->cj_ind = ncj4 * c_nbnxnGpuJgroupSize;
2187
2188         if (nsp_max_av > 0)
2189         {
2190             /* Measure the size of the new entry and potentially split it */
2191             split_sci_entry(nbl, nsp_max_av, progBal, nsp_tot_est, thread, nthread);
2192         }
2193     }
2194     else
2195     {
2196         /* Entry is empty: remove it  */
2197         nbl->sci.pop_back();
2198     }
2199 }
2200
2201 /* Syncs the working array before adding another grid pair to the GPU list */
2202 static void sync_work(NbnxnPairlistCpu gmx_unused* nbl) {}
2203
2204 /* Syncs the working array before adding another grid pair to the GPU list */
2205 static void sync_work(NbnxnPairlistGpu* nbl)
2206 {
2207     nbl->work->cj_ind = nbl->cj4.size() * c_nbnxnGpuJgroupSize;
2208 }
2209
2210 /* Clears an NbnxnPairlistCpu data structure */
2211 static void clear_pairlist(NbnxnPairlistCpu* nbl)
2212 {
2213     nbl->ci.clear();
2214     nbl->cj.clear();
2215     nbl->ncjInUse = 0;
2216     nbl->nci_tot  = 0;
2217     nbl->ciOuter.clear();
2218     nbl->cjOuter.clear();
2219
2220     nbl->work->ncj_noq = 0;
2221     nbl->work->ncj_hlj = 0;
2222 }
2223
2224 /* Clears an NbnxnPairlistGpu data structure */
2225 static void clear_pairlist(NbnxnPairlistGpu* nbl)
2226 {
2227     nbl->sci.clear();
2228     nbl->cj4.clear();
2229     nbl->excl.resize(1);
2230     nbl->nci_tot = 0;
2231 }
2232
2233 /* Clears an atom-atom-style pair list */
2234 static void clear_pairlist_fep(t_nblist* nl)
2235 {
2236     nl->nri = 0;
2237     nl->nrj = 0;
2238     if (nl->jindex == nullptr)
2239     {
2240         snew(nl->jindex, 1);
2241     }
2242     nl->jindex[0] = 0;
2243 }
2244
2245 /* Sets a simple list i-cell bounding box, including PBC shift */
2246 static inline void
2247 set_icell_bb_simple(gmx::ArrayRef<const BoundingBox> bb, int ci, real shx, real shy, real shz, BoundingBox* bb_ci)
2248 {
2249     bb_ci->lower.x = bb[ci].lower.x + shx;
2250     bb_ci->lower.y = bb[ci].lower.y + shy;
2251     bb_ci->lower.z = bb[ci].lower.z + shz;
2252     bb_ci->upper.x = bb[ci].upper.x + shx;
2253     bb_ci->upper.y = bb[ci].upper.y + shy;
2254     bb_ci->upper.z = bb[ci].upper.z + shz;
2255 }
2256
2257 /* Sets a simple list i-cell bounding box, including PBC shift */
2258 static inline void set_icell_bb(const Grid& iGrid, int ci, real shx, real shy, real shz, NbnxnPairlistCpuWork* work)
2259 {
2260     set_icell_bb_simple(iGrid.iBoundingBoxes(), ci, shx, shy, shz, &work->iClusterData.bb[0]);
2261 }
2262
2263 #if NBNXN_BBXXXX
2264 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
2265 static void set_icell_bbxxxx_supersub(gmx::ArrayRef<const float> bb, int ci, real shx, real shy, real shz, float* bb_ci)
2266 {
2267     constexpr int cellBBStride = packedBoundingBoxesIndex(c_gpuNumClusterPerCell);
2268     constexpr int pbbStride    = c_packedBoundingBoxesDimSize;
2269     const int     ia           = ci * cellBBStride;
2270     for (int m = 0; m < cellBBStride; m += c_packedBoundingBoxesSize)
2271     {
2272         for (int i = 0; i < pbbStride; i++)
2273         {
2274             bb_ci[m + 0 * pbbStride + i] = bb[ia + m + 0 * pbbStride + i] + shx;
2275             bb_ci[m + 1 * pbbStride + i] = bb[ia + m + 1 * pbbStride + i] + shy;
2276             bb_ci[m + 2 * pbbStride + i] = bb[ia + m + 2 * pbbStride + i] + shz;
2277             bb_ci[m + 3 * pbbStride + i] = bb[ia + m + 3 * pbbStride + i] + shx;
2278             bb_ci[m + 4 * pbbStride + i] = bb[ia + m + 4 * pbbStride + i] + shy;
2279             bb_ci[m + 5 * pbbStride + i] = bb[ia + m + 5 * pbbStride + i] + shz;
2280         }
2281     }
2282 }
2283 #endif
2284
2285 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
2286 gmx_unused static void set_icell_bb_supersub(gmx::ArrayRef<const BoundingBox> bb,
2287                                              int                              ci,
2288                                              real                             shx,
2289                                              real                             shy,
2290                                              real                             shz,
2291                                              BoundingBox*                     bb_ci)
2292 {
2293     for (int i = 0; i < c_gpuNumClusterPerCell; i++)
2294     {
2295         set_icell_bb_simple(bb, ci * c_gpuNumClusterPerCell + i, shx, shy, shz, &bb_ci[i]);
2296     }
2297 }
2298
2299 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
2300 gmx_unused static void set_icell_bb(const Grid& iGrid, int ci, real shx, real shy, real shz, NbnxnPairlistGpuWork* work)
2301 {
2302 #if NBNXN_BBXXXX
2303     set_icell_bbxxxx_supersub(iGrid.packedBoundingBoxes(), ci, shx, shy, shz,
2304                               work->iSuperClusterData.bbPacked.data());
2305 #else
2306     set_icell_bb_supersub(iGrid.iBoundingBoxes(), ci, shx, shy, shz, work->iSuperClusterData.bb.data());
2307 #endif
2308 }
2309
2310 /* Copies PBC shifted i-cell atom coordinates x,y,z to working array */
2311 static void icell_set_x_simple(int                                 ci,
2312                                real                                shx,
2313                                real                                shy,
2314                                real                                shz,
2315                                int                                 stride,
2316                                const real*                         x,
2317                                NbnxnPairlistCpuWork::IClusterData* iClusterData)
2318 {
2319     const int ia = ci * c_nbnxnCpuIClusterSize;
2320
2321     for (int i = 0; i < c_nbnxnCpuIClusterSize; i++)
2322     {
2323         iClusterData->x[i * STRIDE_XYZ + XX] = x[(ia + i) * stride + XX] + shx;
2324         iClusterData->x[i * STRIDE_XYZ + YY] = x[(ia + i) * stride + YY] + shy;
2325         iClusterData->x[i * STRIDE_XYZ + ZZ] = x[(ia + i) * stride + ZZ] + shz;
2326     }
2327 }
2328
2329 static void icell_set_x(int                             ci,
2330                         real                            shx,
2331                         real                            shy,
2332                         real                            shz,
2333                         int                             stride,
2334                         const real*                     x,
2335                         const ClusterDistanceKernelType kernelType,
2336                         NbnxnPairlistCpuWork*           work)
2337 {
2338     switch (kernelType)
2339     {
2340 #if GMX_SIMD
2341 #    ifdef GMX_NBNXN_SIMD_4XN
2342         case ClusterDistanceKernelType::CpuSimd_4xM:
2343             icell_set_x_simd_4xn(ci, shx, shy, shz, stride, x, work);
2344             break;
2345 #    endif
2346 #    ifdef GMX_NBNXN_SIMD_2XNN
2347         case ClusterDistanceKernelType::CpuSimd_2xMM:
2348             icell_set_x_simd_2xnn(ci, shx, shy, shz, stride, x, work);
2349             break;
2350 #    endif
2351 #endif
2352         case ClusterDistanceKernelType::CpuPlainC:
2353             icell_set_x_simple(ci, shx, shy, shz, stride, x, &work->iClusterData);
2354             break;
2355         default: GMX_ASSERT(false, "Unhandled case"); break;
2356     }
2357 }
2358
2359 /* Copies PBC shifted super-cell atom coordinates x,y,z to working array */
2360 static void icell_set_x(int                       ci,
2361                         real                      shx,
2362                         real                      shy,
2363                         real                      shz,
2364                         int                       stride,
2365                         const real*               x,
2366                         ClusterDistanceKernelType gmx_unused kernelType,
2367                         NbnxnPairlistGpuWork*                work)
2368 {
2369 #if !GMX_SIMD4_HAVE_REAL
2370
2371     real* x_ci = work->iSuperClusterData.x.data();
2372
2373     int ia = ci * c_gpuNumClusterPerCell * c_nbnxnGpuClusterSize;
2374     for (int i = 0; i < c_gpuNumClusterPerCell * c_nbnxnGpuClusterSize; i++)
2375     {
2376         x_ci[i * DIM + XX] = x[(ia + i) * stride + XX] + shx;
2377         x_ci[i * DIM + YY] = x[(ia + i) * stride + YY] + shy;
2378         x_ci[i * DIM + ZZ] = x[(ia + i) * stride + ZZ] + shz;
2379     }
2380
2381 #else /* !GMX_SIMD4_HAVE_REAL */
2382
2383     real* x_ci = work->iSuperClusterData.xSimd.data();
2384
2385     for (int si = 0; si < c_gpuNumClusterPerCell; si++)
2386     {
2387         for (int i = 0; i < c_nbnxnGpuClusterSize; i += GMX_SIMD4_WIDTH)
2388         {
2389             int io = si * c_nbnxnGpuClusterSize + i;
2390             int ia = ci * c_gpuNumClusterPerCell * c_nbnxnGpuClusterSize + io;
2391             for (int j = 0; j < GMX_SIMD4_WIDTH; j++)
2392             {
2393                 x_ci[io * DIM + j + XX * GMX_SIMD4_WIDTH] = x[(ia + j) * stride + XX] + shx;
2394                 x_ci[io * DIM + j + YY * GMX_SIMD4_WIDTH] = x[(ia + j) * stride + YY] + shy;
2395                 x_ci[io * DIM + j + ZZ * GMX_SIMD4_WIDTH] = x[(ia + j) * stride + ZZ] + shz;
2396             }
2397         }
2398     }
2399
2400 #endif /* !GMX_SIMD4_HAVE_REAL */
2401 }
2402
2403 static real minimum_subgrid_size_xy(const Grid& grid)
2404 {
2405     const Grid::Dimensions& dims = grid.dimensions();
2406
2407     if (grid.geometry().isSimple)
2408     {
2409         return std::min(dims.cellSize[XX], dims.cellSize[YY]);
2410     }
2411     else
2412     {
2413         return std::min(dims.cellSize[XX] / c_gpuNumClusterPerCellX,
2414                         dims.cellSize[YY] / c_gpuNumClusterPerCellY);
2415     }
2416 }
2417
2418 static real effective_buffer_1x1_vs_MxN(const Grid& iGrid, const Grid& jGrid)
2419 {
2420     const real eff_1x1_buffer_fac_overest = 0.1;
2421
2422     /* Determine an atom-pair list cut-off buffer size for atom pairs,
2423      * to be added to rlist (including buffer) used for MxN.
2424      * This is for converting an MxN list to a 1x1 list. This means we can't
2425      * use the normal buffer estimate, as we have an MxN list in which
2426      * some atom pairs beyond rlist are missing. We want to capture
2427      * the beneficial effect of buffering by extra pairs just outside rlist,
2428      * while removing the useless pairs that are further away from rlist.
2429      * (Also the buffer could have been set manually not using the estimate.)
2430      * This buffer size is an overestimate.
2431      * We add 10% of the smallest grid sub-cell dimensions.
2432      * Note that the z-size differs per cell and we don't use this,
2433      * so we overestimate.
2434      * With PME, the 10% value gives a buffer that is somewhat larger
2435      * than the effective buffer with a tolerance of 0.005 kJ/mol/ps.
2436      * Smaller tolerances or using RF lead to a smaller effective buffer,
2437      * so 10% gives a safe overestimate.
2438      */
2439     return eff_1x1_buffer_fac_overest * (minimum_subgrid_size_xy(iGrid) + minimum_subgrid_size_xy(jGrid));
2440 }
2441
2442 /* Estimates the interaction volume^2 for non-local interactions */
2443 static real nonlocal_vol2(const struct gmx_domdec_zones_t* zones, const rvec ls, real r)
2444 {
2445     real cl, ca, za;
2446     real vold_est;
2447     real vol2_est_tot;
2448
2449     vol2_est_tot = 0;
2450
2451     /* Here we simply add up the volumes of 1, 2 or 3 1D decomposition
2452      * not home interaction volume^2. As these volumes are not additive,
2453      * this is an overestimate, but it would only be significant in the limit
2454      * of small cells, where we anyhow need to split the lists into
2455      * as small parts as possible.
2456      */
2457
2458     for (int z = 0; z < zones->n; z++)
2459     {
2460         if (zones->shift[z][XX] + zones->shift[z][YY] + zones->shift[z][ZZ] == 1)
2461         {
2462             cl = 0;
2463             ca = 1;
2464             za = 1;
2465             for (int d = 0; d < DIM; d++)
2466             {
2467                 if (zones->shift[z][d] == 0)
2468                 {
2469                     cl += 0.5 * ls[d];
2470                     ca *= ls[d];
2471                     za *= zones->size[z].x1[d] - zones->size[z].x0[d];
2472                 }
2473             }
2474
2475             /* 4 octants of a sphere */
2476             vold_est = 0.25 * M_PI * r * r * r * r;
2477             /* 4 quarter pie slices on the edges */
2478             vold_est += 4 * cl * M_PI / 6.0 * r * r * r;
2479             /* One rectangular volume on a face */
2480             vold_est += ca * 0.5 * r * r;
2481
2482             vol2_est_tot += vold_est * za;
2483         }
2484     }
2485
2486     return vol2_est_tot;
2487 }
2488
2489 /* Estimates the average size of a full j-list for super/sub setup */
2490 static void get_nsubpair_target(const Nbnxm::GridSet&     gridSet,
2491                                 const InteractionLocality iloc,
2492                                 const real                rlist,
2493                                 const int                 min_ci_balanced,
2494                                 int*                      nsubpair_target,
2495                                 float*                    nsubpair_tot_est)
2496 {
2497     /* The target value of 36 seems to be the optimum for Kepler.
2498      * Maxwell is less sensitive to the exact value.
2499      */
2500     const int nsubpair_target_min = 36;
2501     real      r_eff_sup, vol_est, nsp_est, nsp_est_nl;
2502
2503     const Grid& grid = gridSet.grids()[0];
2504
2505     /* We don't need to balance list sizes if:
2506      * - We didn't request balancing.
2507      * - The number of grid cells >= the number of lists requested,
2508      *   since we will always generate at least #cells lists.
2509      * - We don't have any cells, since then there won't be any lists.
2510      */
2511     if (min_ci_balanced <= 0 || grid.numCells() >= min_ci_balanced || grid.numCells() == 0)
2512     {
2513         /* nsubpair_target==0 signals no balancing */
2514         *nsubpair_target  = 0;
2515         *nsubpair_tot_est = 0;
2516
2517         return;
2518     }
2519
2520     gmx::RVec               ls;
2521     const int               numAtomsCluster = grid.geometry().numAtomsICluster;
2522     const Grid::Dimensions& dims            = grid.dimensions();
2523
2524     ls[XX] = dims.cellSize[XX] / c_gpuNumClusterPerCellX;
2525     ls[YY] = dims.cellSize[YY] / c_gpuNumClusterPerCellY;
2526     ls[ZZ] = numAtomsCluster / (dims.atomDensity * ls[XX] * ls[YY]);
2527
2528     /* The formulas below are a heuristic estimate of the average nsj per si*/
2529     r_eff_sup = rlist + nbnxn_get_rlist_effective_inc(numAtomsCluster, ls);
2530
2531     if (!gridSet.domainSetup().haveMultipleDomains || gridSet.domainSetup().zones->n == 1)
2532     {
2533         nsp_est_nl = 0;
2534     }
2535     else
2536     {
2537         nsp_est_nl = gmx::square(dims.atomDensity / numAtomsCluster)
2538                      * nonlocal_vol2(gridSet.domainSetup().zones, ls, r_eff_sup);
2539     }
2540
2541     if (iloc == InteractionLocality::Local)
2542     {
2543         /* Sub-cell interacts with itself */
2544         vol_est = ls[XX] * ls[YY] * ls[ZZ];
2545         /* 6/2 rectangular volume on the faces */
2546         vol_est += (ls[XX] * ls[YY] + ls[XX] * ls[ZZ] + ls[YY] * ls[ZZ]) * r_eff_sup;
2547         /* 12/2 quarter pie slices on the edges */
2548         vol_est += 2 * (ls[XX] + ls[YY] + ls[ZZ]) * 0.25 * M_PI * gmx::square(r_eff_sup);
2549         /* 4 octants of a sphere */
2550         vol_est += 0.5 * 4.0 / 3.0 * M_PI * gmx::power3(r_eff_sup);
2551
2552         /* Estimate the number of cluster pairs as the local number of
2553          * clusters times the volume they interact with times the density.
2554          */
2555         nsp_est = grid.numClusters() * vol_est * dims.atomDensity / numAtomsCluster;
2556
2557         /* Subtract the non-local pair count */
2558         nsp_est -= nsp_est_nl;
2559
2560         /* For small cut-offs nsp_est will be an underesimate.
2561          * With DD nsp_est_nl is an overestimate so nsp_est can get negative.
2562          * So to avoid too small or negative nsp_est we set a minimum of
2563          * all cells interacting with all 3^3 direct neighbors (3^3-1)/2+1=14.
2564          * This might be a slight overestimate for small non-periodic groups of
2565          * atoms as will occur for a local domain with DD, but for small
2566          * groups of atoms we'll anyhow be limited by nsubpair_target_min,
2567          * so this overestimation will not matter.
2568          */
2569         nsp_est = std::max(nsp_est, grid.numClusters() * 14._real);
2570
2571         if (debug)
2572         {
2573             fprintf(debug, "nsp_est local %5.1f non-local %5.1f\n", nsp_est, nsp_est_nl);
2574         }
2575     }
2576     else
2577     {
2578         nsp_est = nsp_est_nl;
2579     }
2580
2581     /* Thus the (average) maximum j-list size should be as follows.
2582      * Since there is overhead, we shouldn't make the lists too small
2583      * (and we can't chop up j-groups) so we use a minimum target size of 36.
2584      */
2585     *nsubpair_target  = std::max(nsubpair_target_min, roundToInt(nsp_est / min_ci_balanced));
2586     *nsubpair_tot_est = nsp_est;
2587
2588     if (debug)
2589     {
2590         fprintf(debug, "nbl nsp estimate %.1f, nsubpair_target %d\n", nsp_est, *nsubpair_target);
2591     }
2592 }
2593
2594 /* Debug list print function */
2595 static void print_nblist_ci_cj(FILE* fp, const NbnxnPairlistCpu& nbl)
2596 {
2597     for (const nbnxn_ci_t& ciEntry : nbl.ci)
2598     {
2599         fprintf(fp, "ci %4d  shift %2d  ncj %3d\n", ciEntry.ci, ciEntry.shift,
2600                 ciEntry.cj_ind_end - ciEntry.cj_ind_start);
2601
2602         for (int j = ciEntry.cj_ind_start; j < ciEntry.cj_ind_end; j++)
2603         {
2604             fprintf(fp, "  cj %5d  imask %x\n", nbl.cj[j].cj, nbl.cj[j].excl);
2605         }
2606     }
2607 }
2608
2609 /* Debug list print function */
2610 static void print_nblist_sci_cj(FILE* fp, const NbnxnPairlistGpu& nbl)
2611 {
2612     for (const nbnxn_sci_t& sci : nbl.sci)
2613     {
2614         fprintf(fp, "ci %4d  shift %2d  ncj4 %2d\n", sci.sci, sci.shift, sci.numJClusterGroups());
2615
2616         int ncp = 0;
2617         for (int j4 = sci.cj4_ind_start; j4 < sci.cj4_ind_end; j4++)
2618         {
2619             for (int j = 0; j < c_nbnxnGpuJgroupSize; j++)
2620             {
2621                 fprintf(fp, "  sj %5d  imask %x\n", nbl.cj4[j4].cj[j], nbl.cj4[j4].imei[0].imask);
2622                 for (int si = 0; si < c_gpuNumClusterPerCell; si++)
2623                 {
2624                     if (nbl.cj4[j4].imei[0].imask & (1U << (j * c_gpuNumClusterPerCell + si)))
2625                     {
2626                         ncp++;
2627                     }
2628                 }
2629             }
2630         }
2631         fprintf(fp, "ci %4d  shift %2d  ncj4 %2d ncp %3d\n", sci.sci, sci.shift,
2632                 sci.numJClusterGroups(), ncp);
2633     }
2634 }
2635
2636 /* Combine pair lists *nbl generated on multiple threads nblc */
2637 static void combine_nblists(gmx::ArrayRef<const NbnxnPairlistGpu> nbls, NbnxnPairlistGpu* nblc)
2638 {
2639     int nsci  = nblc->sci.size();
2640     int ncj4  = nblc->cj4.size();
2641     int nexcl = nblc->excl.size();
2642     for (auto& nbl : nbls)
2643     {
2644         nsci += nbl.sci.size();
2645         ncj4 += nbl.cj4.size();
2646         nexcl += nbl.excl.size();
2647     }
2648
2649     /* Resize with the final, combined size, so we can fill in parallel */
2650     /* NOTE: For better performance we should use default initialization */
2651     nblc->sci.resize(nsci);
2652     nblc->cj4.resize(ncj4);
2653     nblc->excl.resize(nexcl);
2654
2655     /* Each thread should copy its own data to the combined arrays,
2656      * as otherwise data will go back and forth between different caches.
2657      */
2658     const int gmx_unused nthreads = gmx_omp_nthreads_get(emntPairsearch);
2659
2660 #pragma omp parallel for num_threads(nthreads) schedule(static)
2661     for (gmx::index n = 0; n < nbls.ssize(); n++)
2662     {
2663         try
2664         {
2665             /* Determine the offset in the combined data for our thread.
2666              * Note that the original sizes in nblc are lost.
2667              */
2668             int sci_offset  = nsci;
2669             int cj4_offset  = ncj4;
2670             int excl_offset = nexcl;
2671
2672             for (gmx::index i = n; i < nbls.ssize(); i++)
2673             {
2674                 sci_offset -= nbls[i].sci.size();
2675                 cj4_offset -= nbls[i].cj4.size();
2676                 excl_offset -= nbls[i].excl.size();
2677             }
2678
2679             const NbnxnPairlistGpu& nbli = nbls[n];
2680
2681             for (size_t i = 0; i < nbli.sci.size(); i++)
2682             {
2683                 nblc->sci[sci_offset + i] = nbli.sci[i];
2684                 nblc->sci[sci_offset + i].cj4_ind_start += cj4_offset;
2685                 nblc->sci[sci_offset + i].cj4_ind_end += cj4_offset;
2686             }
2687
2688             for (size_t j4 = 0; j4 < nbli.cj4.size(); j4++)
2689             {
2690                 nblc->cj4[cj4_offset + j4] = nbli.cj4[j4];
2691                 nblc->cj4[cj4_offset + j4].imei[0].excl_ind += excl_offset;
2692                 nblc->cj4[cj4_offset + j4].imei[1].excl_ind += excl_offset;
2693             }
2694
2695             for (size_t j4 = 0; j4 < nbli.excl.size(); j4++)
2696             {
2697                 nblc->excl[excl_offset + j4] = nbli.excl[j4];
2698             }
2699         }
2700         GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
2701     }
2702
2703     for (auto& nbl : nbls)
2704     {
2705         nblc->nci_tot += nbl.nci_tot;
2706     }
2707 }
2708
2709 static void balance_fep_lists(gmx::ArrayRef<std::unique_ptr<t_nblist>> fepLists,
2710                               gmx::ArrayRef<PairsearchWork>            work)
2711 {
2712     const int numLists = fepLists.ssize();
2713
2714     if (numLists == 1)
2715     {
2716         /* Nothing to balance */
2717         return;
2718     }
2719
2720     /* Count the total i-lists and pairs */
2721     int nri_tot = 0;
2722     int nrj_tot = 0;
2723     for (const auto& list : fepLists)
2724     {
2725         nri_tot += list->nri;
2726         nrj_tot += list->nrj;
2727     }
2728
2729     const int nrj_target = (nrj_tot + numLists - 1) / numLists;
2730
2731     GMX_ASSERT(gmx_omp_nthreads_get(emntNonbonded) == numLists,
2732                "We should have as many work objects as FEP lists");
2733
2734 #pragma omp parallel for schedule(static) num_threads(numLists)
2735     for (int th = 0; th < numLists; th++)
2736     {
2737         try
2738         {
2739             t_nblist* nbl = work[th].nbl_fep.get();
2740
2741             /* Note that here we allocate for the total size, instead of
2742              * a per-thread esimate (which is hard to obtain).
2743              */
2744             if (nri_tot > nbl->maxnri)
2745             {
2746                 nbl->maxnri = over_alloc_large(nri_tot);
2747                 reallocate_nblist(nbl);
2748             }
2749             if (nri_tot > nbl->maxnri || nrj_tot > nbl->maxnrj)
2750             {
2751                 nbl->maxnrj = over_alloc_small(nrj_tot);
2752                 srenew(nbl->jjnr, nbl->maxnrj);
2753                 srenew(nbl->excl_fep, nbl->maxnrj);
2754             }
2755
2756             clear_pairlist_fep(nbl);
2757         }
2758         GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
2759     }
2760
2761     /* Loop over the source lists and assign and copy i-entries */
2762     int       th_dest = 0;
2763     t_nblist* nbld    = work[th_dest].nbl_fep.get();
2764     for (int th = 0; th < numLists; th++)
2765     {
2766         const t_nblist* nbls = fepLists[th].get();
2767
2768         for (int i = 0; i < nbls->nri; i++)
2769         {
2770             int nrj;
2771
2772             /* The number of pairs in this i-entry */
2773             nrj = nbls->jindex[i + 1] - nbls->jindex[i];
2774
2775             /* Decide if list th_dest is too large and we should procede
2776              * to the next destination list.
2777              */
2778             if (th_dest + 1 < numLists && nbld->nrj > 0
2779                 && nbld->nrj + nrj - nrj_target > nrj_target - nbld->nrj)
2780             {
2781                 th_dest++;
2782                 nbld = work[th_dest].nbl_fep.get();
2783             }
2784
2785             nbld->iinr[nbld->nri]  = nbls->iinr[i];
2786             nbld->gid[nbld->nri]   = nbls->gid[i];
2787             nbld->shift[nbld->nri] = nbls->shift[i];
2788
2789             for (int j = nbls->jindex[i]; j < nbls->jindex[i + 1]; j++)
2790             {
2791                 nbld->jjnr[nbld->nrj]     = nbls->jjnr[j];
2792                 nbld->excl_fep[nbld->nrj] = nbls->excl_fep[j];
2793                 nbld->nrj++;
2794             }
2795             nbld->nri++;
2796             nbld->jindex[nbld->nri] = nbld->nrj;
2797         }
2798     }
2799
2800     /* Swap the list pointers */
2801     for (int th = 0; th < numLists; th++)
2802     {
2803         fepLists[th].swap(work[th].nbl_fep);
2804
2805         if (debug)
2806         {
2807             fprintf(debug, "nbl_fep[%d] nri %4d nrj %4d\n", th, fepLists[th]->nri, fepLists[th]->nrj);
2808         }
2809     }
2810 }
2811
2812 /* Returns the next ci to be processes by our thread */
2813 static gmx_bool next_ci(const Grid& grid, int nth, int ci_block, int* ci_x, int* ci_y, int* ci_b, int* ci)
2814 {
2815     (*ci_b)++;
2816     (*ci)++;
2817
2818     if (*ci_b == ci_block)
2819     {
2820         /* Jump to the next block assigned to this task */
2821         *ci += (nth - 1) * ci_block;
2822         *ci_b = 0;
2823     }
2824
2825     if (*ci >= grid.numCells())
2826     {
2827         return FALSE;
2828     }
2829
2830     while (*ci >= grid.firstCellInColumn(*ci_x * grid.dimensions().numCells[YY] + *ci_y + 1))
2831     {
2832         *ci_y += 1;
2833         if (*ci_y == grid.dimensions().numCells[YY])
2834         {
2835             *ci_x += 1;
2836             *ci_y = 0;
2837         }
2838     }
2839
2840     return TRUE;
2841 }
2842
2843 /* Returns the distance^2 for which we put cell pairs in the list
2844  * without checking atom pair distances. This is usually < rlist^2.
2845  */
2846 static float boundingbox_only_distance2(const Grid::Dimensions& iGridDims,
2847                                         const Grid::Dimensions& jGridDims,
2848                                         real                    rlist,
2849                                         gmx_bool                simple)
2850 {
2851     /* If the distance between two sub-cell bounding boxes is less
2852      * than this distance, do not check the distance between
2853      * all particle pairs in the sub-cell, since then it is likely
2854      * that the box pair has atom pairs within the cut-off.
2855      * We use the nblist cut-off minus 0.5 times the average x/y diagonal
2856      * spacing of the sub-cells. Around 40% of the checked pairs are pruned.
2857      * Using more than 0.5 gains at most 0.5%.
2858      * If forces are calculated more than twice, the performance gain
2859      * in the force calculation outweighs the cost of checking.
2860      * Note that with subcell lists, the atom-pair distance check
2861      * is only performed when only 1 out of 8 sub-cells in within range,
2862      * this is because the GPU is much faster than the cpu.
2863      */
2864     real bbx, bby;
2865     real rbb2;
2866
2867     bbx = 0.5 * (iGridDims.cellSize[XX] + jGridDims.cellSize[XX]);
2868     bby = 0.5 * (iGridDims.cellSize[YY] + jGridDims.cellSize[YY]);
2869     if (!simple)
2870     {
2871         bbx /= c_gpuNumClusterPerCellX;
2872         bby /= c_gpuNumClusterPerCellY;
2873     }
2874
2875     rbb2 = std::max(0.0, rlist - 0.5 * std::sqrt(bbx * bbx + bby * bby));
2876     rbb2 = rbb2 * rbb2;
2877
2878 #if !GMX_DOUBLE
2879     return rbb2;
2880 #else
2881     return (float)((1 + GMX_FLOAT_EPS) * rbb2);
2882 #endif
2883 }
2884
2885 static int get_ci_block_size(const Grid& iGrid, const bool haveMultipleDomains, const int numLists)
2886 {
2887     const int ci_block_enum      = 5;
2888     const int ci_block_denom     = 11;
2889     const int ci_block_min_atoms = 16;
2890     int       ci_block;
2891
2892     /* Here we decide how to distribute the blocks over the threads.
2893      * We use prime numbers to try to avoid that the grid size becomes
2894      * a multiple of the number of threads, which would lead to some
2895      * threads getting "inner" pairs and others getting boundary pairs,
2896      * which in turns will lead to load imbalance between threads.
2897      * Set the block size as 5/11/ntask times the average number of cells
2898      * in a y,z slab. This should ensure a quite uniform distribution
2899      * of the grid parts of the different thread along all three grid
2900      * zone boundaries with 3D domain decomposition. At the same time
2901      * the blocks will not become too small.
2902      */
2903     GMX_ASSERT(iGrid.dimensions().numCells[XX] > 0, "Grid can't be empty");
2904     GMX_ASSERT(numLists > 0, "We need at least one list");
2905     ci_block = (iGrid.numCells() * ci_block_enum)
2906                / (ci_block_denom * iGrid.dimensions().numCells[XX] * numLists);
2907
2908     const int numAtomsPerCell = iGrid.geometry().numAtomsPerCell;
2909
2910     /* Ensure the blocks are not too small: avoids cache invalidation */
2911     if (ci_block * numAtomsPerCell < ci_block_min_atoms)
2912     {
2913         ci_block = (ci_block_min_atoms + numAtomsPerCell - 1) / numAtomsPerCell;
2914     }
2915
2916     /* Without domain decomposition
2917      * or with less than 3 blocks per task, divide in nth blocks.
2918      */
2919     if (!haveMultipleDomains || numLists * 3 * ci_block > iGrid.numCells())
2920     {
2921         ci_block = (iGrid.numCells() + numLists - 1) / numLists;
2922     }
2923
2924     if (ci_block > 1 && (numLists - 1) * ci_block >= iGrid.numCells())
2925     {
2926         /* Some threads have no work. Although reducing the block size
2927          * does not decrease the block count on the first few threads,
2928          * with GPUs better mixing of "upper" cells that have more empty
2929          * clusters results in a somewhat lower max load over all threads.
2930          * Without GPUs the regime of so few atoms per thread is less
2931          * performance relevant, but with 8-wide SIMD the same reasoning
2932          * applies, since the pair list uses 4 i-atom "sub-clusters".
2933          */
2934         ci_block--;
2935     }
2936
2937     return ci_block;
2938 }
2939
2940 /* Returns the number of bits to right-shift a cluster index to obtain
2941  * the corresponding force buffer flag index.
2942  */
2943 static int getBufferFlagShift(int numAtomsPerCluster)
2944 {
2945     int bufferFlagShift = 0;
2946     while ((numAtomsPerCluster << bufferFlagShift) < NBNXN_BUFFERFLAG_SIZE)
2947     {
2948         bufferFlagShift++;
2949     }
2950
2951     return bufferFlagShift;
2952 }
2953
2954 static bool pairlistIsSimple(const NbnxnPairlistCpu gmx_unused& pairlist)
2955 {
2956     return true;
2957 }
2958
2959 static bool pairlistIsSimple(const NbnxnPairlistGpu gmx_unused& pairlist)
2960 {
2961     return false;
2962 }
2963
2964 static void makeClusterListWrapper(NbnxnPairlistCpu* nbl,
2965                                    const Grid gmx_unused&          iGrid,
2966                                    const int                       ci,
2967                                    const Grid&                     jGrid,
2968                                    const int                       firstCell,
2969                                    const int                       lastCell,
2970                                    const bool                      excludeSubDiagonal,
2971                                    const nbnxn_atomdata_t*         nbat,
2972                                    const real                      rlist2,
2973                                    const real                      rbb2,
2974                                    const ClusterDistanceKernelType kernelType,
2975                                    int*                            numDistanceChecks)
2976 {
2977     switch (kernelType)
2978     {
2979         case ClusterDistanceKernelType::CpuPlainC:
2980             makeClusterListSimple(jGrid, nbl, ci, firstCell, lastCell, excludeSubDiagonal,
2981                                   nbat->x().data(), rlist2, rbb2, numDistanceChecks);
2982             break;
2983 #ifdef GMX_NBNXN_SIMD_4XN
2984         case ClusterDistanceKernelType::CpuSimd_4xM:
2985             makeClusterListSimd4xn(jGrid, nbl, ci, firstCell, lastCell, excludeSubDiagonal,
2986                                    nbat->x().data(), rlist2, rbb2, numDistanceChecks);
2987             break;
2988 #endif
2989 #ifdef GMX_NBNXN_SIMD_2XNN
2990         case ClusterDistanceKernelType::CpuSimd_2xMM:
2991             makeClusterListSimd2xnn(jGrid, nbl, ci, firstCell, lastCell, excludeSubDiagonal,
2992                                     nbat->x().data(), rlist2, rbb2, numDistanceChecks);
2993             break;
2994 #endif
2995         default: GMX_ASSERT(false, "Unhandled kernel type");
2996     }
2997 }
2998
2999 static void makeClusterListWrapper(NbnxnPairlistGpu* nbl,
3000                                    const Grid& gmx_unused    iGrid,
3001                                    const int                 ci,
3002                                    const Grid&               jGrid,
3003                                    const int                 firstCell,
3004                                    const int                 lastCell,
3005                                    const bool                excludeSubDiagonal,
3006                                    const nbnxn_atomdata_t*   nbat,
3007                                    const real                rlist2,
3008                                    const real                rbb2,
3009                                    ClusterDistanceKernelType gmx_unused kernelType,
3010                                    int*                                 numDistanceChecks)
3011 {
3012     for (int cj = firstCell; cj <= lastCell; cj++)
3013     {
3014         make_cluster_list_supersub(iGrid, jGrid, nbl, ci, cj, excludeSubDiagonal, nbat->xstride,
3015                                    nbat->x().data(), rlist2, rbb2, numDistanceChecks);
3016     }
3017 }
3018
3019 static int getNumSimpleJClustersInList(const NbnxnPairlistCpu& nbl)
3020 {
3021     return nbl.cj.size();
3022 }
3023
3024 static int getNumSimpleJClustersInList(const gmx_unused NbnxnPairlistGpu& nbl)
3025 {
3026     return 0;
3027 }
3028
3029 static void incrementNumSimpleJClustersInList(NbnxnPairlistCpu* nbl, int ncj_old_j)
3030 {
3031     nbl->ncjInUse += nbl->cj.size();
3032     nbl->ncjInUse -= ncj_old_j;
3033 }
3034
3035 static void incrementNumSimpleJClustersInList(NbnxnPairlistGpu gmx_unused* nbl, int gmx_unused ncj_old_j)
3036 {
3037 }
3038
3039 static void checkListSizeConsistency(const NbnxnPairlistCpu& nbl, const bool haveFreeEnergy)
3040 {
3041     GMX_RELEASE_ASSERT(static_cast<size_t>(nbl.ncjInUse) == nbl.cj.size() || haveFreeEnergy,
3042                        "Without free-energy all cj pair-list entries should be in use. "
3043                        "Note that subsequent code does not make use of the equality, "
3044                        "this check is only here to catch bugs");
3045 }
3046
3047 static void checkListSizeConsistency(const NbnxnPairlistGpu gmx_unused& nbl, bool gmx_unused haveFreeEnergy)
3048 {
3049     /* We currently can not check consistency here */
3050 }
3051
3052 /* Set the buffer flags for newly added entries in the list */
3053 static void setBufferFlags(const NbnxnPairlistCpu& nbl,
3054                            const int               ncj_old_j,
3055                            const int               gridj_flag_shift,
3056                            gmx_bitmask_t*          gridj_flag,
3057                            const int               th)
3058 {
3059     if (gmx::ssize(nbl.cj) > ncj_old_j)
3060     {
3061         int cbFirst = nbl.cj[ncj_old_j].cj >> gridj_flag_shift;
3062         int cbLast  = nbl.cj.back().cj >> gridj_flag_shift;
3063         for (int cb = cbFirst; cb <= cbLast; cb++)
3064         {
3065             bitmask_init_bit(&gridj_flag[cb], th);
3066         }
3067     }
3068 }
3069
3070 static void setBufferFlags(const NbnxnPairlistGpu gmx_unused& nbl,
3071                            int gmx_unused ncj_old_j,
3072                            int gmx_unused gridj_flag_shift,
3073                            gmx_bitmask_t gmx_unused* gridj_flag,
3074                            int gmx_unused th)
3075 {
3076     GMX_ASSERT(false, "This function should never be called");
3077 }
3078
3079 /* Generates the part of pair-list nbl assigned to our thread */
3080 template<typename T>
3081 static void nbnxn_make_pairlist_part(const Nbnxm::GridSet&   gridSet,
3082                                      const Grid&             iGrid,
3083                                      const Grid&             jGrid,
3084                                      PairsearchWork*         work,
3085                                      const nbnxn_atomdata_t* nbat,
3086                                      const t_blocka&         exclusions,
3087                                      real                    rlist,
3088                                      const PairlistType      pairlistType,
3089                                      int                     ci_block,
3090                                      gmx_bool                bFBufferFlag,
3091                                      int                     nsubpair_max,
3092                                      gmx_bool                progBal,
3093                                      float                   nsubpair_tot_est,
3094                                      int                     th,
3095                                      int                     nth,
3096                                      T*                      nbl,
3097                                      t_nblist*               nbl_fep)
3098 {
3099     int            na_cj_2log;
3100     matrix         box;
3101     real           rl_fep2 = 0;
3102     float          rbb2;
3103     int            ci_b, ci, ci_x, ci_y, ci_xy;
3104     ivec           shp;
3105     real           bx0, bx1, by0, by1, bz0, bz1;
3106     real           bz1_frac;
3107     real           d2cx, d2z, d2z_cx, d2z_cy, d2zx, d2zxy, d2xy;
3108     int            cxf, cxl, cyf, cyf_x, cyl;
3109     int            numDistanceChecks;
3110     int            gridi_flag_shift = 0, gridj_flag_shift = 0;
3111     gmx_bitmask_t* gridj_flag = nullptr;
3112     int            ncj_old_i, ncj_old_j;
3113
3114     if (jGrid.geometry().isSimple != pairlistIsSimple(*nbl)
3115         || iGrid.geometry().isSimple != pairlistIsSimple(*nbl))
3116     {
3117         gmx_incons("Grid incompatible with pair-list");
3118     }
3119
3120     sync_work(nbl);
3121     GMX_ASSERT(nbl->na_ci == jGrid.geometry().numAtomsICluster,
3122                "The cluster sizes in the list and grid should match");
3123     nbl->na_cj = JClusterSizePerListType[pairlistType];
3124     na_cj_2log = get_2log(nbl->na_cj);
3125
3126     nbl->rlist = rlist;
3127
3128     if (bFBufferFlag)
3129     {
3130         /* Determine conversion of clusters to flag blocks */
3131         gridi_flag_shift = getBufferFlagShift(nbl->na_ci);
3132         gridj_flag_shift = getBufferFlagShift(nbl->na_cj);
3133
3134         gridj_flag = work->buffer_flags.flag;
3135     }
3136
3137     gridSet.getBox(box);
3138
3139     const bool haveFep = gridSet.haveFep();
3140
3141     const real rlist2 = nbl->rlist * nbl->rlist;
3142
3143     // Select the cluster pair distance kernel type
3144     const ClusterDistanceKernelType kernelType = getClusterDistanceKernelType(pairlistType, *nbat);
3145
3146     if (haveFep && !pairlistIsSimple(*nbl))
3147     {
3148         /* Determine an atom-pair list cut-off distance for FEP atom pairs.
3149          * We should not simply use rlist, since then we would not have
3150          * the small, effective buffering of the NxN lists.
3151          * The buffer is on overestimate, but the resulting cost for pairs
3152          * beyond rlist is neglible compared to the FEP pairs within rlist.
3153          */
3154         rl_fep2 = nbl->rlist + effective_buffer_1x1_vs_MxN(iGrid, jGrid);
3155
3156         if (debug)
3157         {
3158             fprintf(debug, "nbl_fep atom-pair rlist %f\n", rl_fep2);
3159         }
3160         rl_fep2 = rl_fep2 * rl_fep2;
3161     }
3162
3163     const Grid::Dimensions& iGridDims = iGrid.dimensions();
3164     const Grid::Dimensions& jGridDims = jGrid.dimensions();
3165
3166     rbb2 = boundingbox_only_distance2(iGridDims, jGridDims, nbl->rlist, pairlistIsSimple(*nbl));
3167
3168     if (debug)
3169     {
3170         fprintf(debug, "nbl bounding box only distance %f\n", std::sqrt(rbb2));
3171     }
3172
3173     const bool isIntraGridList = (&iGrid == &jGrid);
3174
3175     /* Set the shift range */
3176     for (int d = 0; d < DIM; d++)
3177     {
3178         /* Check if we need periodicity shifts.
3179          * Without PBC or with domain decomposition we don't need them.
3180          */
3181         if (d >= ePBC2npbcdim(gridSet.domainSetup().ePBC)
3182             || gridSet.domainSetup().haveMultipleDomainsPerDim[d])
3183         {
3184             shp[d] = 0;
3185         }
3186         else
3187         {
3188             const real listRangeCellToCell =
3189                     listRangeForGridCellToGridCell(rlist, iGrid.dimensions(), jGrid.dimensions());
3190             if (d == XX && box[XX][XX] - fabs(box[YY][XX]) - fabs(box[ZZ][XX]) < listRangeCellToCell)
3191             {
3192                 shp[d] = 2;
3193             }
3194             else
3195             {
3196                 shp[d] = 1;
3197             }
3198         }
3199     }
3200     const bool                       bSimple = pairlistIsSimple(*nbl);
3201     gmx::ArrayRef<const BoundingBox> bb_i;
3202 #if NBNXN_BBXXXX
3203     gmx::ArrayRef<const float> pbb_i;
3204     if (bSimple)
3205     {
3206         bb_i = iGrid.iBoundingBoxes();
3207     }
3208     else
3209     {
3210         pbb_i = iGrid.packedBoundingBoxes();
3211     }
3212 #else
3213     /* We use the normal bounding box format for both grid types */
3214     bb_i = iGrid.iBoundingBoxes();
3215 #endif
3216     gmx::ArrayRef<const BoundingBox1D> bbcz_i  = iGrid.zBoundingBoxes();
3217     gmx::ArrayRef<const int>           flags_i = iGrid.clusterFlags();
3218     gmx::ArrayRef<const BoundingBox1D> bbcz_j  = jGrid.zBoundingBoxes();
3219     int                                cell0_i = iGrid.cellOffset();
3220
3221     if (debug)
3222     {
3223         fprintf(debug, "nbl nc_i %d col.av. %.1f ci_block %d\n", iGrid.numCells(),
3224                 iGrid.numCells() / static_cast<double>(iGrid.numColumns()), ci_block);
3225     }
3226
3227     numDistanceChecks = 0;
3228
3229     const real listRangeBBToJCell2 =
3230             gmx::square(listRangeForBoundingBoxToGridCell(rlist, jGrid.dimensions()));
3231
3232     /* Initially ci_b and ci to 1 before where we want them to start,
3233      * as they will both be incremented in next_ci.
3234      */
3235     ci_b = -1;
3236     ci   = th * ci_block - 1;
3237     ci_x = 0;
3238     ci_y = 0;
3239     while (next_ci(iGrid, nth, ci_block, &ci_x, &ci_y, &ci_b, &ci))
3240     {
3241         if (bSimple && flags_i[ci] == 0)
3242         {
3243             continue;
3244         }
3245         ncj_old_i = getNumSimpleJClustersInList(*nbl);
3246
3247         d2cx = 0;
3248         if (!isIntraGridList && shp[XX] == 0)
3249         {
3250             if (bSimple)
3251             {
3252                 bx1 = bb_i[ci].upper.x;
3253             }
3254             else
3255             {
3256                 bx1 = iGridDims.lowerCorner[XX] + (real(ci_x) + 1) * iGridDims.cellSize[XX];
3257             }
3258             if (bx1 < jGridDims.lowerCorner[XX])
3259             {
3260                 d2cx = gmx::square(jGridDims.lowerCorner[XX] - bx1);
3261
3262                 if (d2cx >= listRangeBBToJCell2)
3263                 {
3264                     continue;
3265                 }
3266             }
3267         }
3268
3269         ci_xy = ci_x * iGridDims.numCells[YY] + ci_y;
3270
3271         /* Loop over shift vectors in three dimensions */
3272         for (int tz = -shp[ZZ]; tz <= shp[ZZ]; tz++)
3273         {
3274             const real shz = real(tz) * box[ZZ][ZZ];
3275
3276             bz0 = bbcz_i[ci].lower + shz;
3277             bz1 = bbcz_i[ci].upper + shz;
3278
3279             if (tz == 0)
3280             {
3281                 d2z = 0;
3282             }
3283             else if (tz < 0)
3284             {
3285                 d2z = gmx::square(bz1);
3286             }
3287             else
3288             {
3289                 d2z = gmx::square(bz0 - box[ZZ][ZZ]);
3290             }
3291
3292             d2z_cx = d2z + d2cx;
3293
3294             if (d2z_cx >= rlist2)
3295             {
3296                 continue;
3297             }
3298
3299             bz1_frac = bz1 / real(iGrid.numCellsInColumn(ci_xy));
3300             if (bz1_frac < 0)
3301             {
3302                 bz1_frac = 0;
3303             }
3304             /* The check with bz1_frac close to or larger than 1 comes later */
3305
3306             for (int ty = -shp[YY]; ty <= shp[YY]; ty++)
3307             {
3308                 const real shy = real(ty) * box[YY][YY] + real(tz) * box[ZZ][YY];
3309
3310                 if (bSimple)
3311                 {
3312                     by0 = bb_i[ci].lower.y + shy;
3313                     by1 = bb_i[ci].upper.y + shy;
3314                 }
3315                 else
3316                 {
3317                     by0 = iGridDims.lowerCorner[YY] + (real(ci_y)) * iGridDims.cellSize[YY] + shy;
3318                     by1 = iGridDims.lowerCorner[YY] + (real(ci_y) + 1) * iGridDims.cellSize[YY] + shy;
3319                 }
3320
3321                 get_cell_range<YY>(by0, by1, jGridDims, d2z_cx, rlist, &cyf, &cyl);
3322
3323                 if (cyf > cyl)
3324                 {
3325                     continue;
3326                 }
3327
3328                 d2z_cy = d2z;
3329                 if (by1 < jGridDims.lowerCorner[YY])
3330                 {
3331                     d2z_cy += gmx::square(jGridDims.lowerCorner[YY] - by1);
3332                 }
3333                 else if (by0 > jGridDims.upperCorner[YY])
3334                 {
3335                     d2z_cy += gmx::square(by0 - jGridDims.upperCorner[YY]);
3336                 }
3337
3338                 for (int tx = -shp[XX]; tx <= shp[XX]; tx++)
3339                 {
3340                     const int shift = XYZ2IS(tx, ty, tz);
3341
3342                     const bool excludeSubDiagonal = (isIntraGridList && shift == CENTRAL);
3343
3344                     if (c_pbcShiftBackward && isIntraGridList && shift > CENTRAL)
3345                     {
3346                         continue;
3347                     }
3348
3349                     const real shx =
3350                             real(tx) * box[XX][XX] + real(ty) * box[YY][XX] + real(tz) * box[ZZ][XX];
3351
3352                     if (bSimple)
3353                     {
3354                         bx0 = bb_i[ci].lower.x + shx;
3355                         bx1 = bb_i[ci].upper.x + shx;
3356                     }
3357                     else
3358                     {
3359                         bx0 = iGridDims.lowerCorner[XX] + (real(ci_x)) * iGridDims.cellSize[XX] + shx;
3360                         bx1 = iGridDims.lowerCorner[XX] + (real(ci_x) + 1) * iGridDims.cellSize[XX] + shx;
3361                     }
3362
3363                     get_cell_range<XX>(bx0, bx1, jGridDims, d2z_cy, rlist, &cxf, &cxl);
3364
3365                     if (cxf > cxl)
3366                     {
3367                         continue;
3368                     }
3369
3370                     addNewIEntry(nbl, cell0_i + ci, shift, flags_i[ci]);
3371
3372                     if ((!c_pbcShiftBackward || excludeSubDiagonal) && cxf < ci_x)
3373                     {
3374                         /* Leave the pairs with i > j.
3375                          * x is the major index, so skip half of it.
3376                          */
3377                         cxf = ci_x;
3378                     }
3379
3380                     set_icell_bb(iGrid, ci, shx, shy, shz, nbl->work.get());
3381
3382                     icell_set_x(cell0_i + ci, shx, shy, shz, nbat->xstride, nbat->x().data(),
3383                                 kernelType, nbl->work.get());
3384
3385                     for (int cx = cxf; cx <= cxl; cx++)
3386                     {
3387                         const real cx_real = cx;
3388                         d2zx               = d2z;
3389                         if (jGridDims.lowerCorner[XX] + cx_real * jGridDims.cellSize[XX] > bx1)
3390                         {
3391                             d2zx += gmx::square(jGridDims.lowerCorner[XX]
3392                                                 + cx_real * jGridDims.cellSize[XX] - bx1);
3393                         }
3394                         else if (jGridDims.lowerCorner[XX] + (cx_real + 1) * jGridDims.cellSize[XX] < bx0)
3395                         {
3396                             d2zx += gmx::square(jGridDims.lowerCorner[XX]
3397                                                 + (cx_real + 1) * jGridDims.cellSize[XX] - bx0);
3398                         }
3399
3400                         if (isIntraGridList && cx == 0 && (!c_pbcShiftBackward || shift == CENTRAL)
3401                             && cyf < ci_y)
3402                         {
3403                             /* Leave the pairs with i > j.
3404                              * Skip half of y when i and j have the same x.
3405                              */
3406                             cyf_x = ci_y;
3407                         }
3408                         else
3409                         {
3410                             cyf_x = cyf;
3411                         }
3412
3413                         for (int cy = cyf_x; cy <= cyl; cy++)
3414                         {
3415                             const int columnStart =
3416                                     jGrid.firstCellInColumn(cx * jGridDims.numCells[YY] + cy);
3417                             const int columnEnd =
3418                                     jGrid.firstCellInColumn(cx * jGridDims.numCells[YY] + cy + 1);
3419
3420                             const real cy_real = cy;
3421                             d2zxy              = d2zx;
3422                             if (jGridDims.lowerCorner[YY] + cy_real * jGridDims.cellSize[YY] > by1)
3423                             {
3424                                 d2zxy += gmx::square(jGridDims.lowerCorner[YY]
3425                                                      + cy_real * jGridDims.cellSize[YY] - by1);
3426                             }
3427                             else if (jGridDims.lowerCorner[YY] + (cy_real + 1) * jGridDims.cellSize[YY] < by0)
3428                             {
3429                                 d2zxy += gmx::square(jGridDims.lowerCorner[YY]
3430                                                      + (cy_real + 1) * jGridDims.cellSize[YY] - by0);
3431                             }
3432                             if (columnStart < columnEnd && d2zxy < listRangeBBToJCell2)
3433                             {
3434                                 /* To improve efficiency in the common case
3435                                  * of a homogeneous particle distribution,
3436                                  * we estimate the index of the middle cell
3437                                  * in range (midCell). We search down and up
3438                                  * starting from this index.
3439                                  *
3440                                  * Note that the bbcz_j array contains bounds
3441                                  * for i-clusters, thus for clusters of 4 atoms.
3442                                  * For the common case where the j-cluster size
3443                                  * is 8, we could step with a stride of 2,
3444                                  * but we do not do this because it would
3445                                  * complicate this code even more.
3446                                  */
3447                                 int midCell =
3448                                         columnStart
3449                                         + static_cast<int>(bz1_frac
3450                                                            * static_cast<real>(columnEnd - columnStart));
3451                                 if (midCell >= columnEnd)
3452                                 {
3453                                     midCell = columnEnd - 1;
3454                                 }
3455
3456                                 d2xy = d2zxy - d2z;
3457
3458                                 /* Find the lowest cell that can possibly
3459                                  * be within range.
3460                                  * Check if we hit the bottom of the grid,
3461                                  * if the j-cell is below the i-cell and if so,
3462                                  * if it is within range.
3463                                  */
3464                                 int downTestCell = midCell;
3465                                 while (downTestCell >= columnStart
3466                                        && (bbcz_j[downTestCell].upper >= bz0
3467                                            || d2xy + gmx::square(bbcz_j[downTestCell].upper - bz0) < rlist2))
3468                                 {
3469                                     downTestCell--;
3470                                 }
3471                                 int firstCell = downTestCell + 1;
3472
3473                                 /* Find the highest cell that can possibly
3474                                  * be within range.
3475                                  * Check if we hit the top of the grid,
3476                                  * if the j-cell is above the i-cell and if so,
3477                                  * if it is within range.
3478                                  */
3479                                 int upTestCell = midCell + 1;
3480                                 while (upTestCell < columnEnd
3481                                        && (bbcz_j[upTestCell].lower <= bz1
3482                                            || d2xy + gmx::square(bbcz_j[upTestCell].lower - bz1) < rlist2))
3483                                 {
3484                                     upTestCell++;
3485                                 }
3486                                 int lastCell = upTestCell - 1;
3487
3488 #define NBNXN_REFCODE 0
3489 #if NBNXN_REFCODE
3490                                 {
3491                                     /* Simple reference code, for debugging,
3492                                      * overrides the more complex code above.
3493                                      */
3494                                     firstCell = columnEnd;
3495                                     lastCell  = -1;
3496                                     for (int k = columnStart; k < columnEnd; k++)
3497                                     {
3498                                         if (d2xy + gmx::square(bbcz_j[k * NNBSBB_D + 1] - bz0) < rlist2
3499                                             && k < firstCell)
3500                                         {
3501                                             firstCell = k;
3502                                         }
3503                                         if (d2xy + gmx::square(bbcz_j[k * NNBSBB_D] - bz1) < rlist2
3504                                             && k > lastCell)
3505                                         {
3506                                             lastCell = k;
3507                                         }
3508                                     }
3509                                 }
3510 #endif
3511
3512                                 if (isIntraGridList)
3513                                 {
3514                                     /* We want each atom/cell pair only once,
3515                                      * only use cj >= ci.
3516                                      */
3517                                     if (!c_pbcShiftBackward || shift == CENTRAL)
3518                                     {
3519                                         firstCell = std::max(firstCell, ci);
3520                                     }
3521                                 }
3522
3523                                 if (firstCell <= lastCell)
3524                                 {
3525                                     GMX_ASSERT(firstCell >= columnStart && lastCell < columnEnd,
3526                                                "The range should reside within the current grid "
3527                                                "column");
3528
3529                                     /* For f buffer flags with simple lists */
3530                                     ncj_old_j = getNumSimpleJClustersInList(*nbl);
3531
3532                                     makeClusterListWrapper(nbl, iGrid, ci, jGrid, firstCell, lastCell,
3533                                                            excludeSubDiagonal, nbat, rlist2, rbb2,
3534                                                            kernelType, &numDistanceChecks);
3535
3536                                     if (bFBufferFlag)
3537                                     {
3538                                         setBufferFlags(*nbl, ncj_old_j, gridj_flag_shift, gridj_flag, th);
3539                                     }
3540
3541                                     incrementNumSimpleJClustersInList(nbl, ncj_old_j);
3542                                 }
3543                             }
3544                         }
3545                     }
3546
3547                     /* Set the exclusions for this ci list */
3548                     setExclusionsForIEntry(gridSet, nbl, excludeSubDiagonal, na_cj_2log,
3549                                            *getOpenIEntry(nbl), exclusions);
3550
3551                     if (haveFep)
3552                     {
3553                         make_fep_list(gridSet.atomIndices(), nbat, nbl, excludeSubDiagonal,
3554                                       getOpenIEntry(nbl), shx, shy, shz, rl_fep2, iGrid, jGrid, nbl_fep);
3555                     }
3556
3557                     /* Close this ci list */
3558                     closeIEntry(nbl, nsubpair_max, progBal, nsubpair_tot_est, th, nth);
3559                 }
3560             }
3561         }
3562
3563         if (bFBufferFlag && getNumSimpleJClustersInList(*nbl) > ncj_old_i)
3564         {
3565             bitmask_init_bit(&(work->buffer_flags.flag[(iGrid.cellOffset() + ci) >> gridi_flag_shift]), th);
3566         }
3567     }
3568
3569     work->ndistc = numDistanceChecks;
3570
3571     checkListSizeConsistency(*nbl, haveFep);
3572
3573     if (debug)
3574     {
3575         fprintf(debug, "number of distance checks %d\n", numDistanceChecks);
3576
3577         print_nblist_statistics(debug, *nbl, gridSet, rlist);
3578
3579         if (haveFep)
3580         {
3581             fprintf(debug, "nbl FEP list pairs: %d\n", nbl_fep->nrj);
3582         }
3583     }
3584 }
3585
3586 static void reduce_buffer_flags(gmx::ArrayRef<PairsearchWork> searchWork,
3587                                 int                           nsrc,
3588                                 const nbnxn_buffer_flags_t*   dest)
3589 {
3590     for (int s = 0; s < nsrc; s++)
3591     {
3592         gmx_bitmask_t* flag = searchWork[s].buffer_flags.flag;
3593
3594         for (int b = 0; b < dest->nflag; b++)
3595         {
3596             bitmask_union(&(dest->flag[b]), flag[b]);
3597         }
3598     }
3599 }
3600
3601 static void print_reduction_cost(const nbnxn_buffer_flags_t* flags, int nout)
3602 {
3603     int           nelem, nkeep, ncopy, nred, out;
3604     gmx_bitmask_t mask_0;
3605
3606     nelem = 0;
3607     nkeep = 0;
3608     ncopy = 0;
3609     nred  = 0;
3610     bitmask_init_bit(&mask_0, 0);
3611     for (int b = 0; b < flags->nflag; b++)
3612     {
3613         if (bitmask_is_equal(flags->flag[b], mask_0))
3614         {
3615             /* Only flag 0 is set, no copy of reduction required */
3616             nelem++;
3617             nkeep++;
3618         }
3619         else if (!bitmask_is_zero(flags->flag[b]))
3620         {
3621             int c = 0;
3622             for (out = 0; out < nout; out++)
3623             {
3624                 if (bitmask_is_set(flags->flag[b], out))
3625                 {
3626                     c++;
3627                 }
3628             }
3629             nelem += c;
3630             if (c == 1)
3631             {
3632                 ncopy++;
3633             }
3634             else
3635             {
3636                 nred += c;
3637             }
3638         }
3639     }
3640
3641     fprintf(debug,
3642             "nbnxn reduction: #flag %d #list %d elem %4.2f, keep %4.2f copy %4.2f red %4.2f\n",
3643             flags->nflag, nout, nelem / static_cast<double>(flags->nflag),
3644             nkeep / static_cast<double>(flags->nflag), ncopy / static_cast<double>(flags->nflag),
3645             nred / static_cast<double>(flags->nflag));
3646 }
3647
3648 /* Copies the list entries from src to dest when cjStart <= *cjGlobal < cjEnd.
3649  * *cjGlobal is updated with the cj count in src.
3650  * When setFlags==true, flag bit t is set in flag for all i and j clusters.
3651  */
3652 template<bool setFlags>
3653 static void copySelectedListRange(const nbnxn_ci_t* gmx_restrict srcCi,
3654                                   const NbnxnPairlistCpu* gmx_restrict src,
3655                                   NbnxnPairlistCpu* gmx_restrict dest,
3656                                   gmx_bitmask_t*                 flag,
3657                                   int                            iFlagShift,
3658                                   int                            jFlagShift,
3659                                   int                            t)
3660 {
3661     const int ncj = srcCi->cj_ind_end - srcCi->cj_ind_start;
3662
3663     dest->ci.push_back(*srcCi);
3664     dest->ci.back().cj_ind_start = dest->cj.size();
3665     dest->ci.back().cj_ind_end   = dest->ci.back().cj_ind_start + ncj;
3666
3667     if (setFlags)
3668     {
3669         bitmask_init_bit(&flag[srcCi->ci >> iFlagShift], t);
3670     }
3671
3672     for (int j = srcCi->cj_ind_start; j < srcCi->cj_ind_end; j++)
3673     {
3674         dest->cj.push_back(src->cj[j]);
3675
3676         if (setFlags)
3677         {
3678             /* NOTE: This is relatively expensive, since this
3679              * operation is done for all elements in the list,
3680              * whereas at list generation this is done only
3681              * once for each flag entry.
3682              */
3683             bitmask_init_bit(&flag[src->cj[j].cj >> jFlagShift], t);
3684         }
3685     }
3686 }
3687
3688 #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && __GNUC__ == 7
3689 /* Avoid gcc 7 avx512 loop vectorization bug (actually only needed with -mavx512f) */
3690 #    pragma GCC push_options
3691 #    pragma GCC optimize("no-tree-vectorize")
3692 #endif
3693
3694 /* Returns the number of cluster pairs that are in use summed over all lists */
3695 static int countClusterpairs(gmx::ArrayRef<const NbnxnPairlistCpu> pairlists)
3696 {
3697     /* gcc 7 with -mavx512f can miss the contributions of 16 consecutive
3698      * elements to the sum calculated in this loop. Above we have disabled
3699      * loop vectorization to avoid this bug.
3700      */
3701     int ncjTotal = 0;
3702     for (const auto& pairlist : pairlists)
3703     {
3704         ncjTotal += pairlist.ncjInUse;
3705     }
3706     return ncjTotal;
3707 }
3708
3709 #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && __GNUC__ == 7
3710 #    pragma GCC pop_options
3711 #endif
3712
3713 /* This routine re-balances the pairlists such that all are nearly equally
3714  * sized. Only whole i-entries are moved between lists. These are moved
3715  * between the ends of the lists, such that the buffer reduction cost should
3716  * not change significantly.
3717  * Note that all original reduction flags are currently kept. This can lead
3718  * to reduction of parts of the force buffer that could be avoided. But since
3719  * the original lists are quite balanced, this will only give minor overhead.
3720  */
3721 static void rebalanceSimpleLists(gmx::ArrayRef<const NbnxnPairlistCpu> srcSet,
3722                                  gmx::ArrayRef<NbnxnPairlistCpu>       destSet,
3723                                  gmx::ArrayRef<PairsearchWork>         searchWork)
3724 {
3725     const int ncjTotal  = countClusterpairs(srcSet);
3726     const int numLists  = srcSet.ssize();
3727     const int ncjTarget = (ncjTotal + numLists - 1) / numLists;
3728
3729 #pragma omp parallel num_threads(numLists)
3730     {
3731         int t = gmx_omp_get_thread_num();
3732
3733         int cjStart = ncjTarget * t;
3734         int cjEnd   = ncjTarget * (t + 1);
3735
3736         /* The destination pair-list for task/thread t */
3737         NbnxnPairlistCpu& dest = destSet[t];
3738
3739         clear_pairlist(&dest);
3740         dest.na_cj = srcSet[0].na_cj;
3741
3742         /* Note that the flags in the work struct (still) contain flags
3743          * for all entries that are present in srcSet->nbl[t].
3744          */
3745         gmx_bitmask_t* flag = searchWork[t].buffer_flags.flag;
3746
3747         int iFlagShift = getBufferFlagShift(dest.na_ci);
3748         int jFlagShift = getBufferFlagShift(dest.na_cj);
3749
3750         int cjGlobal = 0;
3751         for (int s = 0; s < numLists && cjGlobal < cjEnd; s++)
3752         {
3753             const NbnxnPairlistCpu* src = &srcSet[s];
3754
3755             if (cjGlobal + src->ncjInUse > cjStart)
3756             {
3757                 for (gmx::index i = 0; i < gmx::ssize(src->ci) && cjGlobal < cjEnd; i++)
3758                 {
3759                     const nbnxn_ci_t* srcCi = &src->ci[i];
3760                     int               ncj   = srcCi->cj_ind_end - srcCi->cj_ind_start;
3761                     if (cjGlobal >= cjStart)
3762                     {
3763                         /* If the source list is not our own, we need to set
3764                          * extra flags (the template bool parameter).
3765                          */
3766                         if (s != t)
3767                         {
3768                             copySelectedListRange<true>(srcCi, src, &dest, flag, iFlagShift, jFlagShift, t);
3769                         }
3770                         else
3771                         {
3772                             copySelectedListRange<false>(srcCi, src, &dest, flag, iFlagShift,
3773                                                          jFlagShift, t);
3774                         }
3775                     }
3776                     cjGlobal += ncj;
3777                 }
3778             }
3779             else
3780             {
3781                 cjGlobal += src->ncjInUse;
3782             }
3783         }
3784
3785         dest.ncjInUse = dest.cj.size();
3786     }
3787
3788 #ifndef NDEBUG
3789     const int ncjTotalNew = countClusterpairs(destSet);
3790     GMX_RELEASE_ASSERT(ncjTotalNew == ncjTotal,
3791                        "The total size of the lists before and after rebalancing should match");
3792 #endif
3793 }
3794
3795 /* Returns if the pairlists are so imbalanced that it is worth rebalancing. */
3796 static bool checkRebalanceSimpleLists(gmx::ArrayRef<const NbnxnPairlistCpu> lists)
3797 {
3798     int numLists = lists.ssize();
3799     int ncjMax   = 0;
3800     int ncjTotal = 0;
3801     for (int s = 0; s < numLists; s++)
3802     {
3803         ncjMax = std::max(ncjMax, lists[s].ncjInUse);
3804         ncjTotal += lists[s].ncjInUse;
3805     }
3806     if (debug)
3807     {
3808         fprintf(debug, "Pair-list ncjMax %d ncjTotal %d\n", ncjMax, ncjTotal);
3809     }
3810     /* The rebalancing adds 3% extra time to the search. Heuristically we
3811      * determined that under common conditions the non-bonded kernel balance
3812      * improvement will outweigh this when the imbalance is more than 3%.
3813      * But this will, obviously, depend on search vs kernel time and nstlist.
3814      */
3815     const real rebalanceTolerance = 1.03;
3816
3817     return real(numLists * ncjMax) > real(ncjTotal) * rebalanceTolerance;
3818 }
3819
3820 /* Perform a count (linear) sort to sort the smaller lists to the end.
3821  * This avoids load imbalance on the GPU, as large lists will be
3822  * scheduled and executed first and the smaller lists later.
3823  * Load balancing between multi-processors only happens at the end
3824  * and there smaller lists lead to more effective load balancing.
3825  * The sorting is done on the cj4 count, not on the actual pair counts.
3826  * Not only does this make the sort faster, but it also results in
3827  * better load balancing than using a list sorted on exact load.
3828  * This function swaps the pointer in the pair list to avoid a copy operation.
3829  */
3830 static void sort_sci(NbnxnPairlistGpu* nbl)
3831 {
3832     if (nbl->cj4.size() <= nbl->sci.size())
3833     {
3834         /* nsci = 0 or all sci have size 1, sorting won't change the order */
3835         return;
3836     }
3837
3838     NbnxnPairlistGpuWork& work = *nbl->work;
3839
3840     /* We will distinguish differences up to double the average */
3841     const int m = static_cast<int>((2 * ssize(nbl->cj4)) / ssize(nbl->sci));
3842
3843     /* Resize work.sci_sort so we can sort into it */
3844     work.sci_sort.resize(nbl->sci.size());
3845
3846     std::vector<int>& sort = work.sortBuffer;
3847     /* Set up m + 1 entries in sort, initialized at 0 */
3848     sort.clear();
3849     sort.resize(m + 1, 0);
3850     /* Count the entries of each size */
3851     for (const nbnxn_sci_t& sci : nbl->sci)
3852     {
3853         int i = std::min(m, sci.numJClusterGroups());
3854         sort[i]++;
3855     }
3856     /* Calculate the offset for each count */
3857     int s0  = sort[m];
3858     sort[m] = 0;
3859     for (gmx::index i = m - 1; i >= 0; i--)
3860     {
3861         int s1  = sort[i];
3862         sort[i] = sort[i + 1] + s0;
3863         s0      = s1;
3864     }
3865
3866     /* Sort entries directly into place */
3867     gmx::ArrayRef<nbnxn_sci_t> sci_sort = work.sci_sort;
3868     for (const nbnxn_sci_t& sci : nbl->sci)
3869     {
3870         int i               = std::min(m, sci.numJClusterGroups());
3871         sci_sort[sort[i]++] = sci;
3872     }
3873
3874     /* Swap the sci pointers so we use the new, sorted list */
3875     std::swap(nbl->sci, work.sci_sort);
3876 }
3877
3878 /* Returns the i-zone range for pairlist construction for the give locality */
3879 static Range<int> getIZoneRange(const Nbnxm::GridSet::DomainSetup& domainSetup,
3880                                 const InteractionLocality          locality)
3881 {
3882     if (domainSetup.doTestParticleInsertion)
3883     {
3884         /* With TPI we do grid 1, the inserted molecule, versus grid 0, the rest */
3885         return { 1, 2 };
3886     }
3887     else if (locality == InteractionLocality::Local)
3888     {
3889         /* Local: only zone (grid) 0 vs 0 */
3890         return { 0, 1 };
3891     }
3892     else
3893     {
3894         /* Non-local: we need all i-zones */
3895         return { 0, int(domainSetup.zones->iZones.size()) };
3896     }
3897 }
3898
3899 /* Returns the j-zone range for pairlist construction for the give locality and i-zone */
3900 static Range<int> getJZoneRange(const gmx_domdec_zones_t& ddZones,
3901                                 const InteractionLocality locality,
3902                                 const int                 iZone)
3903 {
3904     if (locality == InteractionLocality::Local)
3905     {
3906         /* Local: zone 0 vs 0 or with TPI 1 vs 0 */
3907         return { 0, 1 };
3908     }
3909     else if (iZone == 0)
3910     {
3911         /* Non-local: we need to avoid the local (zone 0 vs 0) interactions */
3912         return { 1, *ddZones.iZones[iZone].jZoneRange.end() };
3913     }
3914     else
3915     {
3916         /* Non-local with non-local i-zone: use all j-zones */
3917         return ddZones.iZones[iZone].jZoneRange;
3918     }
3919 }
3920
3921 //! Prepares CPU lists produced by the search for dynamic pruning
3922 static void prepareListsForDynamicPruning(gmx::ArrayRef<NbnxnPairlistCpu> lists);
3923
3924 void PairlistSet::constructPairlists(const Nbnxm::GridSet&         gridSet,
3925                                      gmx::ArrayRef<PairsearchWork> searchWork,
3926                                      nbnxn_atomdata_t*             nbat,
3927                                      const t_blocka*               excl,
3928                                      const int                     minimumIlistCountForGpuBalancing,
3929                                      t_nrnb*                       nrnb,
3930                                      SearchCycleCounting*          searchCycleCounting)
3931 {
3932     const real rlist = params_.rlistOuter;
3933
3934     int      nsubpair_target;
3935     float    nsubpair_tot_est;
3936     int      ci_block;
3937     gmx_bool progBal;
3938     int      np_tot, np_noq, np_hlj, nap;
3939
3940     const int numLists = (isCpuType_ ? cpuLists_.size() : gpuLists_.size());
3941
3942     if (debug)
3943     {
3944         fprintf(debug, "ns making %d nblists\n", numLists);
3945     }
3946
3947     nbat->bUseBufferFlags = (nbat->out.size() > 1);
3948     /* We should re-init the flags before making the first list */
3949     if (nbat->bUseBufferFlags && locality_ == InteractionLocality::Local)
3950     {
3951         init_buffer_flags(&nbat->buffer_flags, nbat->numAtoms());
3952     }
3953
3954     if (!isCpuType_ && minimumIlistCountForGpuBalancing > 0)
3955     {
3956         get_nsubpair_target(gridSet, locality_, rlist, minimumIlistCountForGpuBalancing,
3957                             &nsubpair_target, &nsubpair_tot_est);
3958     }
3959     else
3960     {
3961         nsubpair_target  = 0;
3962         nsubpair_tot_est = 0;
3963     }
3964
3965     /* Clear all pair-lists */
3966     for (int th = 0; th < numLists; th++)
3967     {
3968         if (isCpuType_)
3969         {
3970             clear_pairlist(&cpuLists_[th]);
3971         }
3972         else
3973         {
3974             clear_pairlist(&gpuLists_[th]);
3975         }
3976
3977         if (params_.haveFep)
3978         {
3979             clear_pairlist_fep(fepLists_[th].get());
3980         }
3981     }
3982
3983     const gmx_domdec_zones_t& ddZones = *gridSet.domainSetup().zones;
3984
3985     const auto iZoneRange = getIZoneRange(gridSet.domainSetup(), locality_);
3986
3987     for (const int iZone : iZoneRange)
3988     {
3989         const Grid& iGrid = gridSet.grids()[iZone];
3990
3991         const auto jZoneRange = getJZoneRange(ddZones, locality_, iZone);
3992
3993         for (int jZone : jZoneRange)
3994         {
3995             const Grid& jGrid = gridSet.grids()[jZone];
3996
3997             if (debug)
3998             {
3999                 fprintf(debug, "ns search grid %d vs %d\n", iZone, jZone);
4000             }
4001
4002             searchCycleCounting->start(enbsCCsearch);
4003
4004             ci_block = get_ci_block_size(iGrid, gridSet.domainSetup().haveMultipleDomains, numLists);
4005
4006             /* With GPU: generate progressively smaller lists for
4007              * load balancing for local only or non-local with 2 zones.
4008              */
4009             progBal = (locality_ == InteractionLocality::Local || ddZones.n <= 2);
4010
4011 #pragma omp parallel for num_threads(numLists) schedule(static)
4012             for (int th = 0; th < numLists; th++)
4013             {
4014                 try
4015                 {
4016                     /* Re-init the thread-local work flag data before making
4017                      * the first list (not an elegant conditional).
4018                      */
4019                     if (nbat->bUseBufferFlags && (iZone == 0 && jZone == 0))
4020                     {
4021                         init_buffer_flags(&searchWork[th].buffer_flags, nbat->numAtoms());
4022                     }
4023
4024                     if (combineLists_ && th > 0)
4025                     {
4026                         GMX_ASSERT(!isCpuType_, "Can only combine GPU lists");
4027
4028                         clear_pairlist(&gpuLists_[th]);
4029                     }
4030
4031                     PairsearchWork& work = searchWork[th];
4032
4033                     work.cycleCounter.start();
4034
4035                     t_nblist* fepListPtr = (fepLists_.empty() ? nullptr : fepLists_[th].get());
4036
4037                     /* Divide the i cells equally over the pairlists */
4038                     if (isCpuType_)
4039                     {
4040                         nbnxn_make_pairlist_part(gridSet, iGrid, jGrid, &work, nbat, *excl, rlist,
4041                                                  params_.pairlistType, ci_block, nbat->bUseBufferFlags,
4042                                                  nsubpair_target, progBal, nsubpair_tot_est, th,
4043                                                  numLists, &cpuLists_[th], fepListPtr);
4044                     }
4045                     else
4046                     {
4047                         nbnxn_make_pairlist_part(gridSet, iGrid, jGrid, &work, nbat, *excl, rlist,
4048                                                  params_.pairlistType, ci_block, nbat->bUseBufferFlags,
4049                                                  nsubpair_target, progBal, nsubpair_tot_est, th,
4050                                                  numLists, &gpuLists_[th], fepListPtr);
4051                     }
4052
4053                     work.cycleCounter.stop();
4054                 }
4055                 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
4056             }
4057             searchCycleCounting->stop(enbsCCsearch);
4058
4059             np_tot = 0;
4060             np_noq = 0;
4061             np_hlj = 0;
4062             for (int th = 0; th < numLists; th++)
4063             {
4064                 inc_nrnb(nrnb, eNR_NBNXN_DIST2, searchWork[th].ndistc);
4065
4066                 if (isCpuType_)
4067                 {
4068                     const NbnxnPairlistCpu& nbl = cpuLists_[th];
4069                     np_tot += nbl.cj.size();
4070                     np_noq += nbl.work->ncj_noq;
4071                     np_hlj += nbl.work->ncj_hlj;
4072                 }
4073                 else
4074                 {
4075                     const NbnxnPairlistGpu& nbl = gpuLists_[th];
4076                     /* This count ignores potential subsequent pair pruning */
4077                     np_tot += nbl.nci_tot;
4078                 }
4079             }
4080             if (isCpuType_)
4081             {
4082                 nap = cpuLists_[0].na_ci * cpuLists_[0].na_cj;
4083             }
4084             else
4085             {
4086                 nap = gmx::square(gpuLists_[0].na_ci);
4087             }
4088             natpair_ljq_ = (np_tot - np_noq) * nap - np_hlj * nap / 2;
4089             natpair_lj_  = np_noq * nap;
4090             natpair_q_   = np_hlj * nap / 2;
4091
4092             if (combineLists_ && numLists > 1)
4093             {
4094                 GMX_ASSERT(!isCpuType_, "Can only combine GPU lists");
4095
4096                 searchCycleCounting->start(enbsCCcombine);
4097
4098                 combine_nblists(gmx::constArrayRefFromArray(&gpuLists_[1], numLists - 1), &gpuLists_[0]);
4099
4100                 searchCycleCounting->stop(enbsCCcombine);
4101             }
4102         }
4103     }
4104
4105     if (isCpuType_)
4106     {
4107         if (numLists > 1 && checkRebalanceSimpleLists(cpuLists_))
4108         {
4109             rebalanceSimpleLists(cpuLists_, cpuListsWork_, searchWork);
4110
4111             /* Swap the sets of pair lists */
4112             cpuLists_.swap(cpuListsWork_);
4113         }
4114     }
4115     else
4116     {
4117         /* Sort the entries on size, large ones first */
4118         if (combineLists_ || gpuLists_.size() == 1)
4119         {
4120             sort_sci(&gpuLists_[0]);
4121         }
4122         else
4123         {
4124 #pragma omp parallel for num_threads(numLists) schedule(static)
4125             for (int th = 0; th < numLists; th++)
4126             {
4127                 try
4128                 {
4129                     sort_sci(&gpuLists_[th]);
4130                 }
4131                 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
4132             }
4133         }
4134     }
4135
4136     if (nbat->bUseBufferFlags)
4137     {
4138         reduce_buffer_flags(searchWork, numLists, &nbat->buffer_flags);
4139     }
4140
4141     if (gridSet.haveFep())
4142     {
4143         /* Balance the free-energy lists over all the threads */
4144         balance_fep_lists(fepLists_, searchWork);
4145     }
4146
4147     if (isCpuType_)
4148     {
4149         /* This is a fresh list, so not pruned, stored using ci.
4150          * ciOuter is invalid at this point.
4151          */
4152         GMX_ASSERT(cpuLists_[0].ciOuter.empty(), "ciOuter is invalid so it should be empty");
4153     }
4154
4155     /* If we have more than one list, they either got rebalancing (CPU)
4156      * or combined (GPU), so we should dump the final result to debug.
4157      */
4158     if (debug)
4159     {
4160         if (isCpuType_ && cpuLists_.size() > 1)
4161         {
4162             for (auto& cpuList : cpuLists_)
4163             {
4164                 print_nblist_statistics(debug, cpuList, gridSet, rlist);
4165             }
4166         }
4167         else if (!isCpuType_ && gpuLists_.size() > 1)
4168         {
4169             print_nblist_statistics(debug, gpuLists_[0], gridSet, rlist);
4170         }
4171     }
4172
4173     if (debug)
4174     {
4175         if (gmx_debug_at)
4176         {
4177             if (isCpuType_)
4178             {
4179                 for (auto& cpuList : cpuLists_)
4180                 {
4181                     print_nblist_ci_cj(debug, cpuList);
4182                 }
4183             }
4184             else
4185             {
4186                 print_nblist_sci_cj(debug, gpuLists_[0]);
4187             }
4188         }
4189
4190         if (nbat->bUseBufferFlags)
4191         {
4192             print_reduction_cost(&nbat->buffer_flags, numLists);
4193         }
4194     }
4195
4196     if (params_.useDynamicPruning && isCpuType_)
4197     {
4198         prepareListsForDynamicPruning(cpuLists_);
4199     }
4200 }
4201
4202 void PairlistSets::construct(const InteractionLocality iLocality,
4203                              PairSearch*               pairSearch,
4204                              nbnxn_atomdata_t*         nbat,
4205                              const t_blocka*           excl,
4206                              const int64_t             step,
4207                              t_nrnb*                   nrnb)
4208 {
4209     pairlistSet(iLocality).constructPairlists(pairSearch->gridSet(), pairSearch->work(), nbat, excl,
4210                                               minimumIlistCountForGpuBalancing_, nrnb,
4211                                               &pairSearch->cycleCounting_);
4212
4213     if (iLocality == InteractionLocality::Local)
4214     {
4215         outerListCreationStep_ = step;
4216     }
4217     else
4218     {
4219         GMX_RELEASE_ASSERT(outerListCreationStep_ == step,
4220                            "Outer list should be created at the same step as the inner list");
4221     }
4222
4223     /* Special performance logging stuff (env.var. GMX_NBNXN_CYCLE) */
4224     if (iLocality == InteractionLocality::Local)
4225     {
4226         pairSearch->cycleCounting_.searchCount_++;
4227     }
4228     if (pairSearch->cycleCounting_.recordCycles_
4229         && (!pairSearch->gridSet().domainSetup().haveMultipleDomains || iLocality == InteractionLocality::NonLocal)
4230         && pairSearch->cycleCounting_.searchCount_ % 100 == 0)
4231     {
4232         pairSearch->cycleCounting_.printCycles(stderr, pairSearch->work());
4233     }
4234 }
4235
4236 void nonbonded_verlet_t::constructPairlist(const InteractionLocality iLocality,
4237                                            const t_blocka*           excl,
4238                                            int64_t                   step,
4239                                            t_nrnb*                   nrnb)
4240 {
4241     pairlistSets_->construct(iLocality, pairSearch_.get(), nbat.get(), excl, step, nrnb);
4242
4243     if (useGpu())
4244     {
4245         /* Launch the transfer of the pairlist to the GPU.
4246          *
4247          * NOTE: The launch overhead is currently not timed separately
4248          */
4249         Nbnxm::gpu_init_pairlist(gpu_nbv, pairlistSets().pairlistSet(iLocality).gpuList(), iLocality);
4250     }
4251 }
4252
4253 static void prepareListsForDynamicPruning(gmx::ArrayRef<NbnxnPairlistCpu> lists)
4254 {
4255     /* TODO: Restructure the lists so we have actual outer and inner
4256      *       list objects so we can set a single pointer instead of
4257      *       swapping several pointers.
4258      */
4259
4260     for (auto& list : lists)
4261     {
4262         /* The search produced a list in ci/cj.
4263          * Swap the list pointers so we get the outer list is ciOuter,cjOuter
4264          * and we can prune that to get an inner list in ci/cj.
4265          */
4266         GMX_RELEASE_ASSERT(list.ciOuter.empty() && list.cjOuter.empty(),
4267                            "The outer lists should be empty before preparation");
4268
4269         std::swap(list.ci, list.ciOuter);
4270         std::swap(list.cj, list.cjOuter);
4271     }
4272 }