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