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