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