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