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