Sort all includes in src/gromacs
[alexxy/gromacs.git] / src / gromacs / mdlib / nbnxn_search.c
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014, 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 <math.h>
44 #include <string.h>
45
46 #include "gromacs/legacyheaders/gmx_omp_nthreads.h"
47 #include "gromacs/legacyheaders/macros.h"
48 #include "gromacs/legacyheaders/nrnb.h"
49 #include "gromacs/legacyheaders/ns.h"
50 #include "gromacs/legacyheaders/types/commrec.h"
51 #include "gromacs/math/utilities.h"
52 #include "gromacs/math/vec.h"
53 #include "gromacs/mdlib/nb_verlet.h"
54 #include "gromacs/mdlib/nbnxn_atomdata.h"
55 #include "gromacs/mdlib/nbnxn_consts.h"
56 #include "gromacs/pbcutil/ishift.h"
57 #include "gromacs/pbcutil/pbc.h"
58 #include "gromacs/utility/smalloc.h"
59
60 /* nbnxn_internal.h included gromacs/simd/macros.h */
61 #include "gromacs/mdlib/nbnxn_internal.h"
62 #ifdef GMX_SIMD
63 #include "gromacs/simd/vector_operations.h"
64 #endif
65
66 #ifdef NBNXN_SEARCH_BB_SIMD4
67 /* Always use 4-wide SIMD for bounding box calculations */
68
69 #    ifndef GMX_DOUBLE
70 /* Single precision BBs + coordinates, we can also load coordinates with SIMD */
71 #        define NBNXN_SEARCH_SIMD4_FLOAT_X_BB
72 #    endif
73
74 #    if defined NBNXN_SEARCH_SIMD4_FLOAT_X_BB && (GPU_NSUBCELL == 4 || GPU_NSUBCELL == 8)
75 /* Store bounding boxes with x, y and z coordinates in packs of 4 */
76 #        define NBNXN_PBB_SIMD4
77 #    endif
78
79 /* The packed bounding box coordinate stride is always set to 4.
80  * With AVX we could use 8, but that turns out not to be faster.
81  */
82 #    define STRIDE_PBB        4
83 #    define STRIDE_PBB_2LOG   2
84
85 #endif /* NBNXN_SEARCH_BB_SIMD4 */
86
87 #ifdef GMX_NBNXN_SIMD
88
89 /* The functions below are macros as they are performance sensitive */
90
91 /* 4x4 list, pack=4: no complex conversion required */
92 /* i-cluster to j-cluster conversion */
93 #define CI_TO_CJ_J4(ci)   (ci)
94 /* cluster index to coordinate array index conversion */
95 #define X_IND_CI_J4(ci)  ((ci)*STRIDE_P4)
96 #define X_IND_CJ_J4(cj)  ((cj)*STRIDE_P4)
97
98 /* 4x2 list, pack=4: j-cluster size is half the packing width */
99 /* i-cluster to j-cluster conversion */
100 #define CI_TO_CJ_J2(ci)  ((ci)<<1)
101 /* cluster index to coordinate array index conversion */
102 #define X_IND_CI_J2(ci)  ((ci)*STRIDE_P4)
103 #define X_IND_CJ_J2(cj)  (((cj)>>1)*STRIDE_P4 + ((cj) & 1)*(PACK_X4>>1))
104
105 /* 4x8 list, pack=8: i-cluster size is half the packing width */
106 /* i-cluster to j-cluster conversion */
107 #define CI_TO_CJ_J8(ci)  ((ci)>>1)
108 /* cluster index to coordinate array index conversion */
109 #define X_IND_CI_J8(ci)  (((ci)>>1)*STRIDE_P8 + ((ci) & 1)*(PACK_X8>>1))
110 #define X_IND_CJ_J8(cj)  ((cj)*STRIDE_P8)
111
112 /* The j-cluster size is matched to the SIMD width */
113 #if GMX_SIMD_REAL_WIDTH == 2
114 #define CI_TO_CJ_SIMD_4XN(ci)  CI_TO_CJ_J2(ci)
115 #define X_IND_CI_SIMD_4XN(ci)  X_IND_CI_J2(ci)
116 #define X_IND_CJ_SIMD_4XN(cj)  X_IND_CJ_J2(cj)
117 #else
118 #if GMX_SIMD_REAL_WIDTH == 4
119 #define CI_TO_CJ_SIMD_4XN(ci)  CI_TO_CJ_J4(ci)
120 #define X_IND_CI_SIMD_4XN(ci)  X_IND_CI_J4(ci)
121 #define X_IND_CJ_SIMD_4XN(cj)  X_IND_CJ_J4(cj)
122 #else
123 #if GMX_SIMD_REAL_WIDTH == 8
124 #define CI_TO_CJ_SIMD_4XN(ci)  CI_TO_CJ_J8(ci)
125 #define X_IND_CI_SIMD_4XN(ci)  X_IND_CI_J8(ci)
126 #define X_IND_CJ_SIMD_4XN(cj)  X_IND_CJ_J8(cj)
127 /* Half SIMD with j-cluster size */
128 #define CI_TO_CJ_SIMD_2XNN(ci) CI_TO_CJ_J4(ci)
129 #define X_IND_CI_SIMD_2XNN(ci) X_IND_CI_J4(ci)
130 #define X_IND_CJ_SIMD_2XNN(cj) X_IND_CJ_J4(cj)
131 #else
132 #if GMX_SIMD_REAL_WIDTH == 16
133 #define CI_TO_CJ_SIMD_2XNN(ci) CI_TO_CJ_J8(ci)
134 #define X_IND_CI_SIMD_2XNN(ci) X_IND_CI_J8(ci)
135 #define X_IND_CJ_SIMD_2XNN(cj) X_IND_CJ_J8(cj)
136 #else
137 #error "unsupported GMX_SIMD_REAL_WIDTH"
138 #endif
139 #endif
140 #endif
141 #endif
142
143 #endif /* GMX_NBNXN_SIMD */
144
145
146 #ifdef NBNXN_SEARCH_BB_SIMD4
147 /* Store bounding boxes corners as quadruplets: xxxxyyyyzzzz */
148 #define NBNXN_BBXXXX
149 /* Size of bounding box corners quadruplet */
150 #define NNBSBB_XXXX      (NNBSBB_D*DIM*STRIDE_PBB)
151 #endif
152
153 /* We shift the i-particles backward for PBC.
154  * This leads to more conditionals than shifting forward.
155  * We do this to get more balanced pair lists.
156  */
157 #define NBNXN_SHIFT_BACKWARD
158
159
160 /* This define is a lazy way to avoid interdependence of the grid
161  * and searching data structures.
162  */
163 #define NBNXN_NA_SC_MAX (GPU_NSUBCELL*NBNXN_GPU_CLUSTER_SIZE)
164
165
166 static void nbs_cycle_clear(nbnxn_cycle_t *cc)
167 {
168     int i;
169
170     for (i = 0; i < enbsCCnr; i++)
171     {
172         cc[i].count = 0;
173         cc[i].c     = 0;
174     }
175 }
176
177 static double Mcyc_av(const nbnxn_cycle_t *cc)
178 {
179     return (double)cc->c*1e-6/cc->count;
180 }
181
182 static void nbs_cycle_print(FILE *fp, const nbnxn_search_t nbs)
183 {
184     int n;
185     int t;
186
187     fprintf(fp, "\n");
188     fprintf(fp, "ns %4d grid %4.1f search %4.1f red.f %5.3f",
189             nbs->cc[enbsCCgrid].count,
190             Mcyc_av(&nbs->cc[enbsCCgrid]),
191             Mcyc_av(&nbs->cc[enbsCCsearch]),
192             Mcyc_av(&nbs->cc[enbsCCreducef]));
193
194     if (nbs->nthread_max > 1)
195     {
196         if (nbs->cc[enbsCCcombine].count > 0)
197         {
198             fprintf(fp, " comb %5.2f",
199                     Mcyc_av(&nbs->cc[enbsCCcombine]));
200         }
201         fprintf(fp, " s. th");
202         for (t = 0; t < nbs->nthread_max; t++)
203         {
204             fprintf(fp, " %4.1f",
205                     Mcyc_av(&nbs->work[t].cc[enbsCCsearch]));
206         }
207     }
208     fprintf(fp, "\n");
209 }
210
211 static void nbnxn_grid_init(nbnxn_grid_t * grid)
212 {
213     grid->cxy_na      = NULL;
214     grid->cxy_ind     = NULL;
215     grid->cxy_nalloc  = 0;
216     grid->bb          = NULL;
217     grid->bbj         = NULL;
218     grid->nc_nalloc   = 0;
219 }
220
221 static int get_2log(int n)
222 {
223     int log2;
224
225     log2 = 0;
226     while ((1<<log2) < n)
227     {
228         log2++;
229     }
230     if ((1<<log2) != n)
231     {
232         gmx_fatal(FARGS, "nbnxn na_c (%d) is not a power of 2", n);
233     }
234
235     return log2;
236 }
237
238 static int nbnxn_kernel_to_ci_size(int nb_kernel_type)
239 {
240     switch (nb_kernel_type)
241     {
242         case nbnxnk4x4_PlainC:
243         case nbnxnk4xN_SIMD_4xN:
244         case nbnxnk4xN_SIMD_2xNN:
245             return NBNXN_CPU_CLUSTER_I_SIZE;
246         case nbnxnk8x8x8_CUDA:
247         case nbnxnk8x8x8_PlainC:
248             /* The cluster size for super/sub lists is only set here.
249              * Any value should work for the pair-search and atomdata code.
250              * The kernels, of course, might require a particular value.
251              */
252             return NBNXN_GPU_CLUSTER_SIZE;
253         default:
254             gmx_incons("unknown kernel type");
255     }
256
257     return 0;
258 }
259
260 int nbnxn_kernel_to_cj_size(int nb_kernel_type)
261 {
262     int nbnxn_simd_width = 0;
263     int cj_size          = 0;
264
265 #ifdef GMX_NBNXN_SIMD
266     nbnxn_simd_width = GMX_SIMD_REAL_WIDTH;
267 #endif
268
269     switch (nb_kernel_type)
270     {
271         case nbnxnk4x4_PlainC:
272             cj_size = NBNXN_CPU_CLUSTER_I_SIZE;
273             break;
274         case nbnxnk4xN_SIMD_4xN:
275             cj_size = nbnxn_simd_width;
276             break;
277         case nbnxnk4xN_SIMD_2xNN:
278             cj_size = nbnxn_simd_width/2;
279             break;
280         case nbnxnk8x8x8_CUDA:
281         case nbnxnk8x8x8_PlainC:
282             cj_size = nbnxn_kernel_to_ci_size(nb_kernel_type);
283             break;
284         default:
285             gmx_incons("unknown kernel type");
286     }
287
288     return cj_size;
289 }
290
291 static int ci_to_cj(int na_cj_2log, int ci)
292 {
293     switch (na_cj_2log)
294     {
295         case 2: return ci;     break;
296         case 1: return (ci<<1); break;
297         case 3: return (ci>>1); break;
298     }
299
300     return 0;
301 }
302
303 gmx_bool nbnxn_kernel_pairlist_simple(int nb_kernel_type)
304 {
305     if (nb_kernel_type == nbnxnkNotSet)
306     {
307         gmx_fatal(FARGS, "Non-bonded kernel type not set for Verlet-style pair-list.");
308     }
309
310     switch (nb_kernel_type)
311     {
312         case nbnxnk8x8x8_CUDA:
313         case nbnxnk8x8x8_PlainC:
314             return FALSE;
315
316         case nbnxnk4x4_PlainC:
317         case nbnxnk4xN_SIMD_4xN:
318         case nbnxnk4xN_SIMD_2xNN:
319             return TRUE;
320
321         default:
322             gmx_incons("Invalid nonbonded kernel type passed!");
323             return FALSE;
324     }
325 }
326
327 /* Initializes a single nbnxn_pairlist_t data structure */
328 static void nbnxn_init_pairlist_fep(t_nblist *nl)
329 {
330     nl->type        = GMX_NBLIST_INTERACTION_FREE_ENERGY;
331     nl->igeometry   = GMX_NBLIST_GEOMETRY_PARTICLE_PARTICLE;
332     /* The interaction functions are set in the free energy kernel fuction */
333     nl->ivdw        = -1;
334     nl->ivdwmod     = -1;
335     nl->ielec       = -1;
336     nl->ielecmod    = -1;
337
338     nl->maxnri      = 0;
339     nl->maxnrj      = 0;
340     nl->nri         = 0;
341     nl->nrj         = 0;
342     nl->iinr        = NULL;
343     nl->gid         = NULL;
344     nl->shift       = NULL;
345     nl->jindex      = NULL;
346     nl->jjnr        = NULL;
347     nl->excl_fep    = NULL;
348
349 }
350
351 void nbnxn_init_search(nbnxn_search_t    * nbs_ptr,
352                        ivec               *n_dd_cells,
353                        gmx_domdec_zones_t *zones,
354                        gmx_bool            bFEP,
355                        int                 nthread_max)
356 {
357     nbnxn_search_t nbs;
358     int            d, g, t;
359
360     snew(nbs, 1);
361     *nbs_ptr = nbs;
362
363     nbs->bFEP   = bFEP;
364
365     nbs->DomDec = (n_dd_cells != NULL);
366
367     clear_ivec(nbs->dd_dim);
368     nbs->ngrid = 1;
369     if (nbs->DomDec)
370     {
371         nbs->zones = zones;
372
373         for (d = 0; d < DIM; d++)
374         {
375             if ((*n_dd_cells)[d] > 1)
376             {
377                 nbs->dd_dim[d] = 1;
378                 /* Each grid matches a DD zone */
379                 nbs->ngrid *= 2;
380             }
381         }
382     }
383
384     snew(nbs->grid, nbs->ngrid);
385     for (g = 0; g < nbs->ngrid; g++)
386     {
387         nbnxn_grid_init(&nbs->grid[g]);
388     }
389     nbs->cell        = NULL;
390     nbs->cell_nalloc = 0;
391     nbs->a           = NULL;
392     nbs->a_nalloc    = 0;
393
394     nbs->nthread_max = nthread_max;
395
396     /* Initialize the work data structures for each thread */
397     snew(nbs->work, nbs->nthread_max);
398     for (t = 0; t < nbs->nthread_max; t++)
399     {
400         nbs->work[t].cxy_na           = NULL;
401         nbs->work[t].cxy_na_nalloc    = 0;
402         nbs->work[t].sort_work        = NULL;
403         nbs->work[t].sort_work_nalloc = 0;
404
405         snew(nbs->work[t].nbl_fep, 1);
406         nbnxn_init_pairlist_fep(nbs->work[t].nbl_fep);
407     }
408
409     /* Initialize detailed nbsearch cycle counting */
410     nbs->print_cycles = (getenv("GMX_NBNXN_CYCLE") != 0);
411     nbs->search_count = 0;
412     nbs_cycle_clear(nbs->cc);
413     for (t = 0; t < nbs->nthread_max; t++)
414     {
415         nbs_cycle_clear(nbs->work[t].cc);
416     }
417 }
418
419 static real grid_atom_density(int n, rvec corner0, rvec corner1)
420 {
421     rvec size;
422
423     if (n == 0)
424     {
425         /* To avoid zero density we use a minimum of 1 atom */
426         n = 1;
427     }
428
429     rvec_sub(corner1, corner0, size);
430
431     return n/(size[XX]*size[YY]*size[ZZ]);
432 }
433
434 static int set_grid_size_xy(const nbnxn_search_t nbs,
435                             nbnxn_grid_t *grid,
436                             int dd_zone,
437                             int n, rvec corner0, rvec corner1,
438                             real atom_density)
439 {
440     rvec size;
441     int  na_c;
442     real adens, tlen, tlen_x, tlen_y, nc_max;
443     int  t;
444
445     rvec_sub(corner1, corner0, size);
446
447     if (n > grid->na_sc)
448     {
449         assert(atom_density > 0);
450
451         /* target cell length */
452         if (grid->bSimple)
453         {
454             /* To minimize the zero interactions, we should make
455              * the largest of the i/j cell cubic.
456              */
457             na_c = max(grid->na_c, grid->na_cj);
458
459             /* Approximately cubic cells */
460             tlen   = pow(na_c/atom_density, 1.0/3.0);
461             tlen_x = tlen;
462             tlen_y = tlen;
463         }
464         else
465         {
466             /* Approximately cubic sub cells */
467             tlen   = pow(grid->na_c/atom_density, 1.0/3.0);
468             tlen_x = tlen*GPU_NSUBCELL_X;
469             tlen_y = tlen*GPU_NSUBCELL_Y;
470         }
471         /* We round ncx and ncy down, because we get less cell pairs
472          * in the nbsist when the fixed cell dimensions (x,y) are
473          * larger than the variable one (z) than the other way around.
474          */
475         grid->ncx = max(1, (int)(size[XX]/tlen_x));
476         grid->ncy = max(1, (int)(size[YY]/tlen_y));
477     }
478     else
479     {
480         grid->ncx = 1;
481         grid->ncy = 1;
482     }
483
484     grid->sx     = size[XX]/grid->ncx;
485     grid->sy     = size[YY]/grid->ncy;
486     grid->inv_sx = 1/grid->sx;
487     grid->inv_sy = 1/grid->sy;
488
489     if (dd_zone > 0)
490     {
491         /* This is a non-home zone, add an extra row of cells
492          * for particles communicated for bonded interactions.
493          * These can be beyond the cut-off. It doesn't matter where
494          * they end up on the grid, but for performance it's better
495          * if they don't end up in cells that can be within cut-off range.
496          */
497         grid->ncx++;
498         grid->ncy++;
499     }
500
501     /* We need one additional cell entry for particles moved by DD */
502     if (grid->ncx*grid->ncy+1 > grid->cxy_nalloc)
503     {
504         grid->cxy_nalloc = over_alloc_large(grid->ncx*grid->ncy+1);
505         srenew(grid->cxy_na, grid->cxy_nalloc);
506         srenew(grid->cxy_ind, grid->cxy_nalloc+1);
507     }
508     for (t = 0; t < nbs->nthread_max; t++)
509     {
510         if (grid->ncx*grid->ncy+1 > nbs->work[t].cxy_na_nalloc)
511         {
512             nbs->work[t].cxy_na_nalloc = over_alloc_large(grid->ncx*grid->ncy+1);
513             srenew(nbs->work[t].cxy_na, nbs->work[t].cxy_na_nalloc);
514         }
515     }
516
517     /* Worst case scenario of 1 atom in each last cell */
518     if (grid->na_cj <= grid->na_c)
519     {
520         nc_max = n/grid->na_sc + grid->ncx*grid->ncy;
521     }
522     else
523     {
524         nc_max = n/grid->na_sc + grid->ncx*grid->ncy*grid->na_cj/grid->na_c;
525     }
526
527     if (nc_max > grid->nc_nalloc)
528     {
529         grid->nc_nalloc = over_alloc_large(nc_max);
530         srenew(grid->nsubc, grid->nc_nalloc);
531         srenew(grid->bbcz, grid->nc_nalloc*NNBSBB_D);
532
533         sfree_aligned(grid->bb);
534         /* This snew also zeros the contents, this avoid possible
535          * floating exceptions in SIMD with the unused bb elements.
536          */
537         if (grid->bSimple)
538         {
539             snew_aligned(grid->bb, grid->nc_nalloc, 16);
540         }
541         else
542         {
543 #ifdef NBNXN_BBXXXX
544             int pbb_nalloc;
545
546             pbb_nalloc = grid->nc_nalloc*GPU_NSUBCELL/STRIDE_PBB*NNBSBB_XXXX;
547             snew_aligned(grid->pbb, pbb_nalloc, 16);
548 #else
549             snew_aligned(grid->bb, grid->nc_nalloc*GPU_NSUBCELL, 16);
550 #endif
551         }
552
553         if (grid->bSimple)
554         {
555             if (grid->na_cj == grid->na_c)
556             {
557                 grid->bbj = grid->bb;
558             }
559             else
560             {
561                 sfree_aligned(grid->bbj);
562                 snew_aligned(grid->bbj, grid->nc_nalloc*grid->na_c/grid->na_cj, 16);
563             }
564         }
565
566         srenew(grid->flags, grid->nc_nalloc);
567         if (nbs->bFEP)
568         {
569             srenew(grid->fep, grid->nc_nalloc*grid->na_sc/grid->na_c);
570         }
571     }
572
573     copy_rvec(corner0, grid->c0);
574     copy_rvec(corner1, grid->c1);
575
576     return nc_max;
577 }
578
579 /* We need to sort paricles in grid columns on z-coordinate.
580  * As particle are very often distributed homogeneously, we a sorting
581  * algorithm similar to pigeonhole sort. We multiply the z-coordinate
582  * by a factor, cast to an int and try to store in that hole. If the hole
583  * is full, we move this or another particle. A second pass is needed to make
584  * contiguous elements. SORT_GRID_OVERSIZE is the ratio of holes to particles.
585  * 4 is the optimal value for homogeneous particle distribution and allows
586  * for an O(#particles) sort up till distributions were all particles are
587  * concentrated in 1/4 of the space. No NlogN fallback is implemented,
588  * as it can be expensive to detect imhomogeneous particle distributions.
589  * SGSF is the maximum ratio of holes used, in the worst case all particles
590  * end up in the last hole and we need #particles extra holes at the end.
591  */
592 #define SORT_GRID_OVERSIZE 4
593 #define SGSF (SORT_GRID_OVERSIZE + 1)
594
595 /* Sort particle index a on coordinates x along dim.
596  * Backwards tells if we want decreasing iso increasing coordinates.
597  * h0 is the minimum of the coordinate range.
598  * invh is the 1/length of the sorting range.
599  * n_per_h (>=n) is the expected average number of particles per 1/invh
600  * sort is the sorting work array.
601  * sort should have a size of at least n_per_h*SORT_GRID_OVERSIZE + n,
602  * or easier, allocate at least n*SGSF elements.
603  */
604 static void sort_atoms(int dim, gmx_bool Backwards,
605                        int gmx_unused dd_zone,
606                        int *a, int n, rvec *x,
607                        real h0, real invh, int n_per_h,
608                        int *sort)
609 {
610     int nsort, i, c;
611     int zi, zim, zi_min, zi_max;
612     int cp, tmp;
613
614     if (n <= 1)
615     {
616         /* Nothing to do */
617         return;
618     }
619
620 #ifndef NDEBUG
621     if (n > n_per_h)
622     {
623         gmx_incons("n > n_per_h");
624     }
625 #endif
626
627     /* Transform the inverse range height into the inverse hole height */
628     invh *= n_per_h*SORT_GRID_OVERSIZE;
629
630     /* Set nsort to the maximum possible number of holes used.
631      * In worst case all n elements end up in the last bin.
632      */
633     nsort = n_per_h*SORT_GRID_OVERSIZE + n;
634
635     /* Determine the index range used, so we can limit it for the second pass */
636     zi_min = INT_MAX;
637     zi_max = -1;
638
639     /* Sort the particles using a simple index sort */
640     for (i = 0; i < n; i++)
641     {
642         /* The cast takes care of float-point rounding effects below zero.
643          * This code assumes particles are less than 1/SORT_GRID_OVERSIZE
644          * times the box height out of the box.
645          */
646         zi = (int)((x[a[i]][dim] - h0)*invh);
647
648 #ifndef NDEBUG
649         /* As we can have rounding effect, we use > iso >= here */
650         if (zi < 0 || (dd_zone == 0 && zi > n_per_h*SORT_GRID_OVERSIZE))
651         {
652             gmx_fatal(FARGS, "(int)((x[%d][%c]=%f - %f)*%f) = %d, not in 0 - %d*%d\n",
653                       a[i], 'x'+dim, x[a[i]][dim], h0, invh, zi,
654                       n_per_h, SORT_GRID_OVERSIZE);
655         }
656 #endif
657
658         /* In a non-local domain, particles communcated for bonded interactions
659          * can be far beyond the grid size, which is set by the non-bonded
660          * cut-off distance. We sort such particles into the last cell.
661          */
662         if (zi > n_per_h*SORT_GRID_OVERSIZE)
663         {
664             zi = n_per_h*SORT_GRID_OVERSIZE;
665         }
666
667         /* Ideally this particle should go in sort cell zi,
668          * but that might already be in use,
669          * in that case find the first empty cell higher up
670          */
671         if (sort[zi] < 0)
672         {
673             sort[zi] = a[i];
674             zi_min   = min(zi_min, zi);
675             zi_max   = max(zi_max, zi);
676         }
677         else
678         {
679             /* We have multiple atoms in the same sorting slot.
680              * Sort on real z for minimal bounding box size.
681              * There is an extra check for identical z to ensure
682              * well-defined output order, independent of input order
683              * to ensure binary reproducibility after restarts.
684              */
685             while (sort[zi] >= 0 && ( x[a[i]][dim] >  x[sort[zi]][dim] ||
686                                       (x[a[i]][dim] == x[sort[zi]][dim] &&
687                                        a[i] > sort[zi])))
688             {
689                 zi++;
690             }
691
692             if (sort[zi] >= 0)
693             {
694                 /* Shift all elements by one slot until we find an empty slot */
695                 cp  = sort[zi];
696                 zim = zi + 1;
697                 while (sort[zim] >= 0)
698                 {
699                     tmp       = sort[zim];
700                     sort[zim] = cp;
701                     cp        = tmp;
702                     zim++;
703                 }
704                 sort[zim] = cp;
705                 zi_max    = max(zi_max, zim);
706             }
707             sort[zi] = a[i];
708             zi_max   = max(zi_max, zi);
709         }
710     }
711
712     c = 0;
713     if (!Backwards)
714     {
715         for (zi = 0; zi < nsort; zi++)
716         {
717             if (sort[zi] >= 0)
718             {
719                 a[c++]   = sort[zi];
720                 sort[zi] = -1;
721             }
722         }
723     }
724     else
725     {
726         for (zi = zi_max; zi >= zi_min; zi--)
727         {
728             if (sort[zi] >= 0)
729             {
730                 a[c++]   = sort[zi];
731                 sort[zi] = -1;
732             }
733         }
734     }
735     if (c < n)
736     {
737         gmx_incons("Lost particles while sorting");
738     }
739 }
740
741 #ifdef GMX_DOUBLE
742 #define R2F_D(x) ((float)((x) >= 0 ? ((1-GMX_FLOAT_EPS)*(x)) : ((1+GMX_FLOAT_EPS)*(x))))
743 #define R2F_U(x) ((float)((x) >= 0 ? ((1+GMX_FLOAT_EPS)*(x)) : ((1-GMX_FLOAT_EPS)*(x))))
744 #else
745 #define R2F_D(x) (x)
746 #define R2F_U(x) (x)
747 #endif
748
749 /* Coordinate order x,y,z, bb order xyz0 */
750 static void calc_bounding_box(int na, int stride, const real *x, nbnxn_bb_t *bb)
751 {
752     int  i, j;
753     real xl, xh, yl, yh, zl, zh;
754
755     i  = 0;
756     xl = x[i+XX];
757     xh = x[i+XX];
758     yl = x[i+YY];
759     yh = x[i+YY];
760     zl = x[i+ZZ];
761     zh = x[i+ZZ];
762     i += stride;
763     for (j = 1; j < na; j++)
764     {
765         xl = min(xl, x[i+XX]);
766         xh = max(xh, x[i+XX]);
767         yl = min(yl, x[i+YY]);
768         yh = max(yh, x[i+YY]);
769         zl = min(zl, x[i+ZZ]);
770         zh = max(zh, x[i+ZZ]);
771         i += stride;
772     }
773     /* Note: possible double to float conversion here */
774     bb->lower[BB_X] = R2F_D(xl);
775     bb->lower[BB_Y] = R2F_D(yl);
776     bb->lower[BB_Z] = R2F_D(zl);
777     bb->upper[BB_X] = R2F_U(xh);
778     bb->upper[BB_Y] = R2F_U(yh);
779     bb->upper[BB_Z] = R2F_U(zh);
780 }
781
782 /* Packed coordinates, bb order xyz0 */
783 static void calc_bounding_box_x_x4(int na, const real *x, nbnxn_bb_t *bb)
784 {
785     int  j;
786     real xl, xh, yl, yh, zl, zh;
787
788     xl = x[XX*PACK_X4];
789     xh = x[XX*PACK_X4];
790     yl = x[YY*PACK_X4];
791     yh = x[YY*PACK_X4];
792     zl = x[ZZ*PACK_X4];
793     zh = x[ZZ*PACK_X4];
794     for (j = 1; j < na; j++)
795     {
796         xl = min(xl, x[j+XX*PACK_X4]);
797         xh = max(xh, x[j+XX*PACK_X4]);
798         yl = min(yl, x[j+YY*PACK_X4]);
799         yh = max(yh, x[j+YY*PACK_X4]);
800         zl = min(zl, x[j+ZZ*PACK_X4]);
801         zh = max(zh, x[j+ZZ*PACK_X4]);
802     }
803     /* Note: possible double to float conversion here */
804     bb->lower[BB_X] = R2F_D(xl);
805     bb->lower[BB_Y] = R2F_D(yl);
806     bb->lower[BB_Z] = R2F_D(zl);
807     bb->upper[BB_X] = R2F_U(xh);
808     bb->upper[BB_Y] = R2F_U(yh);
809     bb->upper[BB_Z] = R2F_U(zh);
810 }
811
812 /* Packed coordinates, bb order xyz0 */
813 static void calc_bounding_box_x_x8(int na, const real *x, nbnxn_bb_t *bb)
814 {
815     int  j;
816     real xl, xh, yl, yh, zl, zh;
817
818     xl = x[XX*PACK_X8];
819     xh = x[XX*PACK_X8];
820     yl = x[YY*PACK_X8];
821     yh = x[YY*PACK_X8];
822     zl = x[ZZ*PACK_X8];
823     zh = x[ZZ*PACK_X8];
824     for (j = 1; j < na; j++)
825     {
826         xl = min(xl, x[j+XX*PACK_X8]);
827         xh = max(xh, x[j+XX*PACK_X8]);
828         yl = min(yl, x[j+YY*PACK_X8]);
829         yh = max(yh, x[j+YY*PACK_X8]);
830         zl = min(zl, x[j+ZZ*PACK_X8]);
831         zh = max(zh, x[j+ZZ*PACK_X8]);
832     }
833     /* Note: possible double to float conversion here */
834     bb->lower[BB_X] = R2F_D(xl);
835     bb->lower[BB_Y] = R2F_D(yl);
836     bb->lower[BB_Z] = R2F_D(zl);
837     bb->upper[BB_X] = R2F_U(xh);
838     bb->upper[BB_Y] = R2F_U(yh);
839     bb->upper[BB_Z] = R2F_U(zh);
840 }
841
842 /* Packed coordinates, bb order xyz0 */
843 static void calc_bounding_box_x_x4_halves(int na, const real *x,
844                                           nbnxn_bb_t *bb, nbnxn_bb_t *bbj)
845 {
846     calc_bounding_box_x_x4(min(na, 2), x, bbj);
847
848     if (na > 2)
849     {
850         calc_bounding_box_x_x4(min(na-2, 2), x+(PACK_X4>>1), bbj+1);
851     }
852     else
853     {
854         /* Set the "empty" bounding box to the same as the first one,
855          * so we don't need to treat special cases in the rest of the code.
856          */
857 #ifdef NBNXN_SEARCH_BB_SIMD4
858         gmx_simd4_store_f(&bbj[1].lower[0], gmx_simd4_load_f(&bbj[0].lower[0]));
859         gmx_simd4_store_f(&bbj[1].upper[0], gmx_simd4_load_f(&bbj[0].upper[0]));
860 #else
861         bbj[1] = bbj[0];
862 #endif
863     }
864
865 #ifdef NBNXN_SEARCH_BB_SIMD4
866     gmx_simd4_store_f(&bb->lower[0],
867                       gmx_simd4_min_f(gmx_simd4_load_f(&bbj[0].lower[0]),
868                                       gmx_simd4_load_f(&bbj[1].lower[0])));
869     gmx_simd4_store_f(&bb->upper[0],
870                       gmx_simd4_max_f(gmx_simd4_load_f(&bbj[0].upper[0]),
871                                       gmx_simd4_load_f(&bbj[1].upper[0])));
872 #else
873     {
874         int i;
875
876         for (i = 0; i < NNBSBB_C; i++)
877         {
878             bb->lower[i] = min(bbj[0].lower[i], bbj[1].lower[i]);
879             bb->upper[i] = max(bbj[0].upper[i], bbj[1].upper[i]);
880         }
881     }
882 #endif
883 }
884
885 #ifdef NBNXN_SEARCH_BB_SIMD4
886
887 /* Coordinate order xyz, bb order xxxxyyyyzzzz */
888 static void calc_bounding_box_xxxx(int na, int stride, const real *x, float *bb)
889 {
890     int  i, j;
891     real xl, xh, yl, yh, zl, zh;
892
893     i  = 0;
894     xl = x[i+XX];
895     xh = x[i+XX];
896     yl = x[i+YY];
897     yh = x[i+YY];
898     zl = x[i+ZZ];
899     zh = x[i+ZZ];
900     i += stride;
901     for (j = 1; j < na; j++)
902     {
903         xl = min(xl, x[i+XX]);
904         xh = max(xh, x[i+XX]);
905         yl = min(yl, x[i+YY]);
906         yh = max(yh, x[i+YY]);
907         zl = min(zl, x[i+ZZ]);
908         zh = max(zh, x[i+ZZ]);
909         i += stride;
910     }
911     /* Note: possible double to float conversion here */
912     bb[0*STRIDE_PBB] = R2F_D(xl);
913     bb[1*STRIDE_PBB] = R2F_D(yl);
914     bb[2*STRIDE_PBB] = R2F_D(zl);
915     bb[3*STRIDE_PBB] = R2F_U(xh);
916     bb[4*STRIDE_PBB] = R2F_U(yh);
917     bb[5*STRIDE_PBB] = R2F_U(zh);
918 }
919
920 #endif /* NBNXN_SEARCH_BB_SIMD4 */
921
922 #ifdef NBNXN_SEARCH_SIMD4_FLOAT_X_BB
923
924 /* Coordinate order xyz?, bb order xyz0 */
925 static void calc_bounding_box_simd4(int na, const float *x, nbnxn_bb_t *bb)
926 {
927     gmx_simd4_float_t bb_0_S, bb_1_S;
928     gmx_simd4_float_t x_S;
929
930     int               i;
931
932     bb_0_S = gmx_simd4_load_f(x);
933     bb_1_S = bb_0_S;
934
935     for (i = 1; i < na; i++)
936     {
937         x_S    = gmx_simd4_load_f(x+i*NNBSBB_C);
938         bb_0_S = gmx_simd4_min_f(bb_0_S, x_S);
939         bb_1_S = gmx_simd4_max_f(bb_1_S, x_S);
940     }
941
942     gmx_simd4_store_f(&bb->lower[0], bb_0_S);
943     gmx_simd4_store_f(&bb->upper[0], bb_1_S);
944 }
945
946 /* Coordinate order xyz?, bb order xxxxyyyyzzzz */
947 static void calc_bounding_box_xxxx_simd4(int na, const float *x,
948                                          nbnxn_bb_t *bb_work_aligned,
949                                          real *bb)
950 {
951     calc_bounding_box_simd4(na, x, bb_work_aligned);
952
953     bb[0*STRIDE_PBB] = bb_work_aligned->lower[BB_X];
954     bb[1*STRIDE_PBB] = bb_work_aligned->lower[BB_Y];
955     bb[2*STRIDE_PBB] = bb_work_aligned->lower[BB_Z];
956     bb[3*STRIDE_PBB] = bb_work_aligned->upper[BB_X];
957     bb[4*STRIDE_PBB] = bb_work_aligned->upper[BB_Y];
958     bb[5*STRIDE_PBB] = bb_work_aligned->upper[BB_Z];
959 }
960
961 #endif /* NBNXN_SEARCH_SIMD4_FLOAT_X_BB */
962
963
964 /* Combines pairs of consecutive bounding boxes */
965 static void combine_bounding_box_pairs(nbnxn_grid_t *grid, const nbnxn_bb_t *bb)
966 {
967     int    i, j, sc2, nc2, c2;
968
969     for (i = 0; i < grid->ncx*grid->ncy; i++)
970     {
971         /* Starting bb in a column is expected to be 2-aligned */
972         sc2 = grid->cxy_ind[i]>>1;
973         /* For odd numbers skip the last bb here */
974         nc2 = (grid->cxy_na[i]+3)>>(2+1);
975         for (c2 = sc2; c2 < sc2+nc2; c2++)
976         {
977 #ifdef NBNXN_SEARCH_BB_SIMD4
978             gmx_simd4_float_t min_S, max_S;
979
980             min_S = gmx_simd4_min_f(gmx_simd4_load_f(&bb[c2*2+0].lower[0]),
981                                     gmx_simd4_load_f(&bb[c2*2+1].lower[0]));
982             max_S = gmx_simd4_max_f(gmx_simd4_load_f(&bb[c2*2+0].upper[0]),
983                                     gmx_simd4_load_f(&bb[c2*2+1].upper[0]));
984             gmx_simd4_store_f(&grid->bbj[c2].lower[0], min_S);
985             gmx_simd4_store_f(&grid->bbj[c2].upper[0], max_S);
986 #else
987             for (j = 0; j < NNBSBB_C; j++)
988             {
989                 grid->bbj[c2].lower[j] = min(bb[c2*2+0].lower[j],
990                                              bb[c2*2+1].lower[j]);
991                 grid->bbj[c2].upper[j] = max(bb[c2*2+0].upper[j],
992                                              bb[c2*2+1].upper[j]);
993             }
994 #endif
995         }
996         if (((grid->cxy_na[i]+3)>>2) & 1)
997         {
998             /* The bb count in this column is odd: duplicate the last bb */
999             for (j = 0; j < NNBSBB_C; j++)
1000             {
1001                 grid->bbj[c2].lower[j] = bb[c2*2].lower[j];
1002                 grid->bbj[c2].upper[j] = bb[c2*2].upper[j];
1003             }
1004         }
1005     }
1006 }
1007
1008
1009 /* Prints the average bb size, used for debug output */
1010 static void print_bbsizes_simple(FILE                *fp,
1011                                  const nbnxn_search_t nbs,
1012                                  const nbnxn_grid_t  *grid)
1013 {
1014     int  c, d;
1015     dvec ba;
1016
1017     clear_dvec(ba);
1018     for (c = 0; c < grid->nc; c++)
1019     {
1020         for (d = 0; d < DIM; d++)
1021         {
1022             ba[d] += grid->bb[c].upper[d] - grid->bb[c].lower[d];
1023         }
1024     }
1025     dsvmul(1.0/grid->nc, ba, ba);
1026
1027     fprintf(fp, "ns bb: %4.2f %4.2f %4.2f  %4.2f %4.2f %4.2f rel %4.2f %4.2f %4.2f\n",
1028             nbs->box[XX][XX]/grid->ncx,
1029             nbs->box[YY][YY]/grid->ncy,
1030             nbs->box[ZZ][ZZ]*grid->ncx*grid->ncy/grid->nc,
1031             ba[XX], ba[YY], ba[ZZ],
1032             ba[XX]*grid->ncx/nbs->box[XX][XX],
1033             ba[YY]*grid->ncy/nbs->box[YY][YY],
1034             ba[ZZ]*grid->nc/(grid->ncx*grid->ncy*nbs->box[ZZ][ZZ]));
1035 }
1036
1037 /* Prints the average bb size, used for debug output */
1038 static void print_bbsizes_supersub(FILE                *fp,
1039                                    const nbnxn_search_t nbs,
1040                                    const nbnxn_grid_t  *grid)
1041 {
1042     int  ns, c, s;
1043     dvec ba;
1044
1045     clear_dvec(ba);
1046     ns = 0;
1047     for (c = 0; c < grid->nc; c++)
1048     {
1049 #ifdef NBNXN_BBXXXX
1050         for (s = 0; s < grid->nsubc[c]; s += STRIDE_PBB)
1051         {
1052             int cs_w, i, d;
1053
1054             cs_w = (c*GPU_NSUBCELL + s)/STRIDE_PBB;
1055             for (i = 0; i < STRIDE_PBB; i++)
1056             {
1057                 for (d = 0; d < DIM; d++)
1058                 {
1059                     ba[d] +=
1060                         grid->pbb[cs_w*NNBSBB_XXXX+(DIM+d)*STRIDE_PBB+i] -
1061                         grid->pbb[cs_w*NNBSBB_XXXX+     d *STRIDE_PBB+i];
1062                 }
1063             }
1064         }
1065 #else
1066         for (s = 0; s < grid->nsubc[c]; s++)
1067         {
1068             int cs, d;
1069
1070             cs = c*GPU_NSUBCELL + s;
1071             for (d = 0; d < DIM; d++)
1072             {
1073                 ba[d] += grid->bb[cs].upper[d] - grid->bb[cs].lower[d];
1074             }
1075         }
1076 #endif
1077         ns += grid->nsubc[c];
1078     }
1079     dsvmul(1.0/ns, ba, ba);
1080
1081     fprintf(fp, "ns bb: %4.2f %4.2f %4.2f  %4.2f %4.2f %4.2f rel %4.2f %4.2f %4.2f\n",
1082             nbs->box[XX][XX]/(grid->ncx*GPU_NSUBCELL_X),
1083             nbs->box[YY][YY]/(grid->ncy*GPU_NSUBCELL_Y),
1084             nbs->box[ZZ][ZZ]*grid->ncx*grid->ncy/(grid->nc*GPU_NSUBCELL_Z),
1085             ba[XX], ba[YY], ba[ZZ],
1086             ba[XX]*grid->ncx*GPU_NSUBCELL_X/nbs->box[XX][XX],
1087             ba[YY]*grid->ncy*GPU_NSUBCELL_Y/nbs->box[YY][YY],
1088             ba[ZZ]*grid->nc*GPU_NSUBCELL_Z/(grid->ncx*grid->ncy*nbs->box[ZZ][ZZ]));
1089 }
1090
1091 /* Potentially sorts atoms on LJ coefficients !=0 and ==0.
1092  * Also sets interaction flags.
1093  */
1094 void sort_on_lj(int na_c,
1095                 int a0, int a1, const int *atinfo,
1096                 int *order,
1097                 int *flags)
1098 {
1099     int      subc, s, a, n1, n2, a_lj_max, i, j;
1100     int      sort1[NBNXN_NA_SC_MAX/GPU_NSUBCELL];
1101     int      sort2[NBNXN_NA_SC_MAX/GPU_NSUBCELL];
1102     gmx_bool haveQ, bFEP;
1103
1104     *flags = 0;
1105
1106     subc = 0;
1107     for (s = a0; s < a1; s += na_c)
1108     {
1109         /* Make lists for this (sub-)cell on atoms with and without LJ */
1110         n1       = 0;
1111         n2       = 0;
1112         haveQ    = FALSE;
1113         a_lj_max = -1;
1114         for (a = s; a < min(s+na_c, a1); a++)
1115         {
1116             haveQ = haveQ || GET_CGINFO_HAS_Q(atinfo[order[a]]);
1117
1118             if (GET_CGINFO_HAS_VDW(atinfo[order[a]]))
1119             {
1120                 sort1[n1++] = order[a];
1121                 a_lj_max    = a;
1122             }
1123             else
1124             {
1125                 sort2[n2++] = order[a];
1126             }
1127         }
1128
1129         /* If we don't have atoms with LJ, there's nothing to sort */
1130         if (n1 > 0)
1131         {
1132             *flags |= NBNXN_CI_DO_LJ(subc);
1133
1134             if (2*n1 <= na_c)
1135             {
1136                 /* Only sort when strictly necessary. Ordering particles
1137                  * Ordering particles can lead to less accurate summation
1138                  * due to rounding, both for LJ and Coulomb interactions.
1139                  */
1140                 if (2*(a_lj_max - s) >= na_c)
1141                 {
1142                     for (i = 0; i < n1; i++)
1143                     {
1144                         order[a0+i] = sort1[i];
1145                     }
1146                     for (j = 0; j < n2; j++)
1147                     {
1148                         order[a0+n1+j] = sort2[j];
1149                     }
1150                 }
1151
1152                 *flags |= NBNXN_CI_HALF_LJ(subc);
1153             }
1154         }
1155         if (haveQ)
1156         {
1157             *flags |= NBNXN_CI_DO_COUL(subc);
1158         }
1159         subc++;
1160     }
1161 }
1162
1163 /* Fill a pair search cell with atoms.
1164  * Potentially sorts atoms and sets the interaction flags.
1165  */
1166 void fill_cell(const nbnxn_search_t nbs,
1167                nbnxn_grid_t *grid,
1168                nbnxn_atomdata_t *nbat,
1169                int a0, int a1,
1170                const int *atinfo,
1171                rvec *x,
1172                int sx, int sy, int sz,
1173                nbnxn_bb_t gmx_unused *bb_work_aligned)
1174 {
1175     int         na, a;
1176     size_t      offset;
1177     nbnxn_bb_t *bb_ptr;
1178 #ifdef NBNXN_BBXXXX
1179     float      *pbb_ptr;
1180 #endif
1181
1182     na = a1 - a0;
1183
1184     if (grid->bSimple)
1185     {
1186         sort_on_lj(grid->na_c, a0, a1, atinfo, nbs->a,
1187                    grid->flags+(a0>>grid->na_c_2log)-grid->cell0);
1188     }
1189
1190     if (nbs->bFEP)
1191     {
1192         /* Set the fep flag for perturbed atoms in this (sub-)cell */
1193         int c, at;
1194
1195         /* The grid-local cluster/(sub-)cell index */
1196         c            = (a0 >> grid->na_c_2log) - grid->cell0*(grid->bSimple ? 1 : GPU_NSUBCELL);
1197         grid->fep[c] = 0;
1198         for (at = a0; at < a1; at++)
1199         {
1200             if (nbs->a[at] >= 0 && GET_CGINFO_FEP(atinfo[nbs->a[at]]))
1201             {
1202                 grid->fep[c] |= (1 << (at - a0));
1203             }
1204         }
1205     }
1206
1207     /* Now we have sorted the atoms, set the cell indices */
1208     for (a = a0; a < a1; a++)
1209     {
1210         nbs->cell[nbs->a[a]] = a;
1211     }
1212
1213     copy_rvec_to_nbat_real(nbs->a+a0, a1-a0, grid->na_c, x,
1214                            nbat->XFormat, nbat->x, a0,
1215                            sx, sy, sz);
1216
1217     if (nbat->XFormat == nbatX4)
1218     {
1219         /* Store the bounding boxes as xyz.xyz. */
1220         offset = (a0 - grid->cell0*grid->na_sc) >> grid->na_c_2log;
1221         bb_ptr = grid->bb + offset;
1222
1223 #if defined GMX_NBNXN_SIMD && GMX_SIMD_REAL_WIDTH == 2
1224         if (2*grid->na_cj == grid->na_c)
1225         {
1226             calc_bounding_box_x_x4_halves(na, nbat->x+X4_IND_A(a0), bb_ptr,
1227                                           grid->bbj+offset*2);
1228         }
1229         else
1230 #endif
1231         {
1232             calc_bounding_box_x_x4(na, nbat->x+X4_IND_A(a0), bb_ptr);
1233         }
1234     }
1235     else if (nbat->XFormat == nbatX8)
1236     {
1237         /* Store the bounding boxes as xyz.xyz. */
1238         offset = (a0 - grid->cell0*grid->na_sc) >> grid->na_c_2log;
1239         bb_ptr = grid->bb + offset;
1240
1241         calc_bounding_box_x_x8(na, nbat->x+X8_IND_A(a0), bb_ptr);
1242     }
1243 #ifdef NBNXN_BBXXXX
1244     else if (!grid->bSimple)
1245     {
1246         /* Store the bounding boxes in a format convenient
1247          * for SIMD4 calculations: xxxxyyyyzzzz...
1248          */
1249         pbb_ptr =
1250             grid->pbb +
1251             ((a0-grid->cell0*grid->na_sc)>>(grid->na_c_2log+STRIDE_PBB_2LOG))*NNBSBB_XXXX +
1252             (((a0-grid->cell0*grid->na_sc)>>grid->na_c_2log) & (STRIDE_PBB-1));
1253
1254 #ifdef NBNXN_SEARCH_SIMD4_FLOAT_X_BB
1255         if (nbat->XFormat == nbatXYZQ)
1256         {
1257             calc_bounding_box_xxxx_simd4(na, nbat->x+a0*nbat->xstride,
1258                                          bb_work_aligned, pbb_ptr);
1259         }
1260         else
1261 #endif
1262         {
1263             calc_bounding_box_xxxx(na, nbat->xstride, nbat->x+a0*nbat->xstride,
1264                                    pbb_ptr);
1265         }
1266         if (gmx_debug_at)
1267         {
1268             fprintf(debug, "%2d %2d %2d bb %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f\n",
1269                     sx, sy, sz,
1270                     pbb_ptr[0*STRIDE_PBB], pbb_ptr[3*STRIDE_PBB],
1271                     pbb_ptr[1*STRIDE_PBB], pbb_ptr[4*STRIDE_PBB],
1272                     pbb_ptr[2*STRIDE_PBB], pbb_ptr[5*STRIDE_PBB]);
1273         }
1274     }
1275 #endif
1276     else
1277     {
1278         /* Store the bounding boxes as xyz.xyz. */
1279         bb_ptr = grid->bb+((a0-grid->cell0*grid->na_sc)>>grid->na_c_2log);
1280
1281         calc_bounding_box(na, nbat->xstride, nbat->x+a0*nbat->xstride,
1282                           bb_ptr);
1283
1284         if (gmx_debug_at)
1285         {
1286             int bbo;
1287             bbo = (a0 - grid->cell0*grid->na_sc)/grid->na_c;
1288             fprintf(debug, "%2d %2d %2d bb %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f\n",
1289                     sx, sy, sz,
1290                     grid->bb[bbo].lower[BB_X],
1291                     grid->bb[bbo].lower[BB_Y],
1292                     grid->bb[bbo].lower[BB_Z],
1293                     grid->bb[bbo].upper[BB_X],
1294                     grid->bb[bbo].upper[BB_Y],
1295                     grid->bb[bbo].upper[BB_Z]);
1296         }
1297     }
1298 }
1299
1300 /* Spatially sort the atoms within one grid column */
1301 static void sort_columns_simple(const nbnxn_search_t nbs,
1302                                 int dd_zone,
1303                                 nbnxn_grid_t *grid,
1304                                 int a0, int a1,
1305                                 const int *atinfo,
1306                                 rvec *x,
1307                                 nbnxn_atomdata_t *nbat,
1308                                 int cxy_start, int cxy_end,
1309                                 int *sort_work)
1310 {
1311     int  cxy;
1312     int  cx, cy, cz, ncz, cfilled, c;
1313     int  na, ash, ind, a;
1314     int  na_c, ash_c;
1315
1316     if (debug)
1317     {
1318         fprintf(debug, "cell0 %d sorting columns %d - %d, atoms %d - %d\n",
1319                 grid->cell0, cxy_start, cxy_end, a0, a1);
1320     }
1321
1322     /* Sort the atoms within each x,y column in 3 dimensions */
1323     for (cxy = cxy_start; cxy < cxy_end; cxy++)
1324     {
1325         cx = cxy/grid->ncy;
1326         cy = cxy - cx*grid->ncy;
1327
1328         na  = grid->cxy_na[cxy];
1329         ncz = grid->cxy_ind[cxy+1] - grid->cxy_ind[cxy];
1330         ash = (grid->cell0 + grid->cxy_ind[cxy])*grid->na_sc;
1331
1332         /* Sort the atoms within each x,y column on z coordinate */
1333         sort_atoms(ZZ, FALSE, dd_zone,
1334                    nbs->a+ash, na, x,
1335                    grid->c0[ZZ],
1336                    1.0/nbs->box[ZZ][ZZ], ncz*grid->na_sc,
1337                    sort_work);
1338
1339         /* Fill the ncz cells in this column */
1340         cfilled = grid->cxy_ind[cxy];
1341         for (cz = 0; cz < ncz; cz++)
1342         {
1343             c  = grid->cxy_ind[cxy] + cz;
1344
1345             ash_c = ash + cz*grid->na_sc;
1346             na_c  = min(grid->na_sc, na-(ash_c-ash));
1347
1348             fill_cell(nbs, grid, nbat,
1349                       ash_c, ash_c+na_c, atinfo, x,
1350                       grid->na_sc*cx + (dd_zone >> 2),
1351                       grid->na_sc*cy + (dd_zone & 3),
1352                       grid->na_sc*cz,
1353                       NULL);
1354
1355             /* This copy to bbcz is not really necessary.
1356              * But it allows to use the same grid search code
1357              * for the simple and supersub cell setups.
1358              */
1359             if (na_c > 0)
1360             {
1361                 cfilled = c;
1362             }
1363             grid->bbcz[c*NNBSBB_D  ] = grid->bb[cfilled].lower[BB_Z];
1364             grid->bbcz[c*NNBSBB_D+1] = grid->bb[cfilled].upper[BB_Z];
1365         }
1366
1367         /* Set the unused atom indices to -1 */
1368         for (ind = na; ind < ncz*grid->na_sc; ind++)
1369         {
1370             nbs->a[ash+ind] = -1;
1371         }
1372     }
1373 }
1374
1375 /* Spatially sort the atoms within one grid column */
1376 static void sort_columns_supersub(const nbnxn_search_t nbs,
1377                                   int dd_zone,
1378                                   nbnxn_grid_t *grid,
1379                                   int a0, int a1,
1380                                   const int *atinfo,
1381                                   rvec *x,
1382                                   nbnxn_atomdata_t *nbat,
1383                                   int cxy_start, int cxy_end,
1384                                   int *sort_work)
1385 {
1386     int        cxy;
1387     int        cx, cy, cz = -1, c = -1, ncz;
1388     int        na, ash, na_c, ind, a;
1389     int        subdiv_z, sub_z, na_z, ash_z;
1390     int        subdiv_y, sub_y, na_y, ash_y;
1391     int        subdiv_x, sub_x, na_x, ash_x;
1392
1393     nbnxn_bb_t bb_work_array[2], *bb_work_aligned;
1394
1395     bb_work_aligned = (nbnxn_bb_t *)(((size_t)(bb_work_array+1)) & (~((size_t)15)));
1396
1397     if (debug)
1398     {
1399         fprintf(debug, "cell0 %d sorting columns %d - %d, atoms %d - %d\n",
1400                 grid->cell0, cxy_start, cxy_end, a0, a1);
1401     }
1402
1403     subdiv_x = grid->na_c;
1404     subdiv_y = GPU_NSUBCELL_X*subdiv_x;
1405     subdiv_z = GPU_NSUBCELL_Y*subdiv_y;
1406
1407     /* Sort the atoms within each x,y column in 3 dimensions */
1408     for (cxy = cxy_start; cxy < cxy_end; cxy++)
1409     {
1410         cx = cxy/grid->ncy;
1411         cy = cxy - cx*grid->ncy;
1412
1413         na  = grid->cxy_na[cxy];
1414         ncz = grid->cxy_ind[cxy+1] - grid->cxy_ind[cxy];
1415         ash = (grid->cell0 + grid->cxy_ind[cxy])*grid->na_sc;
1416
1417         /* Sort the atoms within each x,y column on z coordinate */
1418         sort_atoms(ZZ, FALSE, dd_zone,
1419                    nbs->a+ash, na, x,
1420                    grid->c0[ZZ],
1421                    1.0/nbs->box[ZZ][ZZ], ncz*grid->na_sc,
1422                    sort_work);
1423
1424         /* This loop goes over the supercells and subcells along z at once */
1425         for (sub_z = 0; sub_z < ncz*GPU_NSUBCELL_Z; sub_z++)
1426         {
1427             ash_z = ash + sub_z*subdiv_z;
1428             na_z  = min(subdiv_z, na-(ash_z-ash));
1429
1430             /* We have already sorted on z */
1431
1432             if (sub_z % GPU_NSUBCELL_Z == 0)
1433             {
1434                 cz = sub_z/GPU_NSUBCELL_Z;
1435                 c  = grid->cxy_ind[cxy] + cz;
1436
1437                 /* The number of atoms in this supercell */
1438                 na_c = min(grid->na_sc, na-(ash_z-ash));
1439
1440                 grid->nsubc[c] = min(GPU_NSUBCELL, (na_c+grid->na_c-1)/grid->na_c);
1441
1442                 /* Store the z-boundaries of the super cell */
1443                 grid->bbcz[c*NNBSBB_D  ] = x[nbs->a[ash_z]][ZZ];
1444                 grid->bbcz[c*NNBSBB_D+1] = x[nbs->a[ash_z+na_c-1]][ZZ];
1445             }
1446
1447 #if GPU_NSUBCELL_Y > 1
1448             /* Sort the atoms along y */
1449             sort_atoms(YY, (sub_z & 1), dd_zone,
1450                        nbs->a+ash_z, na_z, x,
1451                        grid->c0[YY]+cy*grid->sy,
1452                        grid->inv_sy, subdiv_z,
1453                        sort_work);
1454 #endif
1455
1456             for (sub_y = 0; sub_y < GPU_NSUBCELL_Y; sub_y++)
1457             {
1458                 ash_y = ash_z + sub_y*subdiv_y;
1459                 na_y  = min(subdiv_y, na-(ash_y-ash));
1460
1461 #if GPU_NSUBCELL_X > 1
1462                 /* Sort the atoms along x */
1463                 sort_atoms(XX, ((cz*GPU_NSUBCELL_Y + sub_y) & 1), dd_zone,
1464                            nbs->a+ash_y, na_y, x,
1465                            grid->c0[XX]+cx*grid->sx,
1466                            grid->inv_sx, subdiv_y,
1467                            sort_work);
1468 #endif
1469
1470                 for (sub_x = 0; sub_x < GPU_NSUBCELL_X; sub_x++)
1471                 {
1472                     ash_x = ash_y + sub_x*subdiv_x;
1473                     na_x  = min(subdiv_x, na-(ash_x-ash));
1474
1475                     fill_cell(nbs, grid, nbat,
1476                               ash_x, ash_x+na_x, atinfo, x,
1477                               grid->na_c*(cx*GPU_NSUBCELL_X+sub_x) + (dd_zone >> 2),
1478                               grid->na_c*(cy*GPU_NSUBCELL_Y+sub_y) + (dd_zone & 3),
1479                               grid->na_c*sub_z,
1480                               bb_work_aligned);
1481                 }
1482             }
1483         }
1484
1485         /* Set the unused atom indices to -1 */
1486         for (ind = na; ind < ncz*grid->na_sc; ind++)
1487         {
1488             nbs->a[ash+ind] = -1;
1489         }
1490     }
1491 }
1492
1493 /* Determine in which grid column atoms should go */
1494 static void calc_column_indices(nbnxn_grid_t *grid,
1495                                 int a0, int a1,
1496                                 rvec *x,
1497                                 int dd_zone, const int *move,
1498                                 int thread, int nthread,
1499                                 int *cell,
1500                                 int *cxy_na)
1501 {
1502     int  n0, n1, i;
1503     int  cx, cy;
1504
1505     /* We add one extra cell for particles which moved during DD */
1506     for (i = 0; i < grid->ncx*grid->ncy+1; i++)
1507     {
1508         cxy_na[i] = 0;
1509     }
1510
1511     n0 = a0 + (int)((thread+0)*(a1 - a0))/nthread;
1512     n1 = a0 + (int)((thread+1)*(a1 - a0))/nthread;
1513     if (dd_zone == 0)
1514     {
1515         /* Home zone */
1516         for (i = n0; i < n1; i++)
1517         {
1518             if (move == NULL || move[i] >= 0)
1519             {
1520                 /* We need to be careful with rounding,
1521                  * particles might be a few bits outside the local zone.
1522                  * The int cast takes care of the lower bound,
1523                  * we will explicitly take care of the upper bound.
1524                  */
1525                 cx = (int)((x[i][XX] - grid->c0[XX])*grid->inv_sx);
1526                 cy = (int)((x[i][YY] - grid->c0[YY])*grid->inv_sy);
1527
1528 #ifndef NDEBUG
1529                 if (cx < 0 || cx > grid->ncx ||
1530                     cy < 0 || cy > grid->ncy)
1531                 {
1532                     gmx_fatal(FARGS,
1533                               "grid cell cx %d cy %d out of range (max %d %d)\n"
1534                               "atom %f %f %f, grid->c0 %f %f",
1535                               cx, cy, grid->ncx, grid->ncy,
1536                               x[i][XX], x[i][YY], x[i][ZZ], grid->c0[XX], grid->c0[YY]);
1537                 }
1538 #endif
1539                 /* Take care of potential rouding issues */
1540                 cx = min(cx, grid->ncx - 1);
1541                 cy = min(cy, grid->ncy - 1);
1542
1543                 /* For the moment cell will contain only the, grid local,
1544                  * x and y indices, not z.
1545                  */
1546                 cell[i] = cx*grid->ncy + cy;
1547             }
1548             else
1549             {
1550                 /* Put this moved particle after the end of the grid,
1551                  * so we can process it later without using conditionals.
1552                  */
1553                 cell[i] = grid->ncx*grid->ncy;
1554             }
1555
1556             cxy_na[cell[i]]++;
1557         }
1558     }
1559     else
1560     {
1561         /* Non-home zone */
1562         for (i = n0; i < n1; i++)
1563         {
1564             cx = (int)((x[i][XX] - grid->c0[XX])*grid->inv_sx);
1565             cy = (int)((x[i][YY] - grid->c0[YY])*grid->inv_sy);
1566
1567             /* For non-home zones there could be particles outside
1568              * the non-bonded cut-off range, which have been communicated
1569              * for bonded interactions only. For the result it doesn't
1570              * matter where these end up on the grid. For performance
1571              * we put them in an extra row at the border.
1572              */
1573             cx = max(cx, 0);
1574             cx = min(cx, grid->ncx - 1);
1575             cy = max(cy, 0);
1576             cy = min(cy, grid->ncy - 1);
1577
1578             /* For the moment cell will contain only the, grid local,
1579              * x and y indices, not z.
1580              */
1581             cell[i] = cx*grid->ncy + cy;
1582
1583             cxy_na[cell[i]]++;
1584         }
1585     }
1586 }
1587
1588 /* Determine in which grid cells the atoms should go */
1589 static void calc_cell_indices(const nbnxn_search_t nbs,
1590                               int dd_zone,
1591                               nbnxn_grid_t *grid,
1592                               int a0, int a1,
1593                               const int *atinfo,
1594                               rvec *x,
1595                               const int *move,
1596                               nbnxn_atomdata_t *nbat)
1597 {
1598     int   n0, n1, i;
1599     int   cx, cy, cxy, ncz_max, ncz;
1600     int   nthread, thread;
1601     int  *cxy_na, cxy_na_i;
1602
1603     nthread = gmx_omp_nthreads_get(emntPairsearch);
1604
1605 #pragma omp parallel for num_threads(nthread) schedule(static)
1606     for (thread = 0; thread < nthread; thread++)
1607     {
1608         calc_column_indices(grid, a0, a1, x, dd_zone, move, thread, nthread,
1609                             nbs->cell, nbs->work[thread].cxy_na);
1610     }
1611
1612     /* Make the cell index as a function of x and y */
1613     ncz_max          = 0;
1614     ncz              = 0;
1615     grid->cxy_ind[0] = 0;
1616     for (i = 0; i < grid->ncx*grid->ncy+1; i++)
1617     {
1618         /* We set ncz_max at the beginning of the loop iso at the end
1619          * to skip i=grid->ncx*grid->ncy which are moved particles
1620          * that do not need to be ordered on the grid.
1621          */
1622         if (ncz > ncz_max)
1623         {
1624             ncz_max = ncz;
1625         }
1626         cxy_na_i = nbs->work[0].cxy_na[i];
1627         for (thread = 1; thread < nthread; thread++)
1628         {
1629             cxy_na_i += nbs->work[thread].cxy_na[i];
1630         }
1631         ncz = (cxy_na_i + grid->na_sc - 1)/grid->na_sc;
1632         if (nbat->XFormat == nbatX8)
1633         {
1634             /* Make the number of cell a multiple of 2 */
1635             ncz = (ncz + 1) & ~1;
1636         }
1637         grid->cxy_ind[i+1] = grid->cxy_ind[i] + ncz;
1638         /* Clear cxy_na, so we can reuse the array below */
1639         grid->cxy_na[i] = 0;
1640     }
1641     grid->nc = grid->cxy_ind[grid->ncx*grid->ncy] - grid->cxy_ind[0];
1642
1643     nbat->natoms = (grid->cell0 + grid->nc)*grid->na_sc;
1644
1645     if (debug)
1646     {
1647         fprintf(debug, "ns na_sc %d na_c %d super-cells: %d x %d y %d z %.1f maxz %d\n",
1648                 grid->na_sc, grid->na_c, grid->nc,
1649                 grid->ncx, grid->ncy, grid->nc/((double)(grid->ncx*grid->ncy)),
1650                 ncz_max);
1651         if (gmx_debug_at)
1652         {
1653             i = 0;
1654             for (cy = 0; cy < grid->ncy; cy++)
1655             {
1656                 for (cx = 0; cx < grid->ncx; cx++)
1657                 {
1658                     fprintf(debug, " %2d", grid->cxy_ind[i+1]-grid->cxy_ind[i]);
1659                     i++;
1660                 }
1661                 fprintf(debug, "\n");
1662             }
1663         }
1664     }
1665
1666     /* Make sure the work array for sorting is large enough */
1667     if (ncz_max*grid->na_sc*SGSF > nbs->work[0].sort_work_nalloc)
1668     {
1669         for (thread = 0; thread < nbs->nthread_max; thread++)
1670         {
1671             nbs->work[thread].sort_work_nalloc =
1672                 over_alloc_large(ncz_max*grid->na_sc*SGSF);
1673             srenew(nbs->work[thread].sort_work,
1674                    nbs->work[thread].sort_work_nalloc);
1675             /* When not in use, all elements should be -1 */
1676             for (i = 0; i < nbs->work[thread].sort_work_nalloc; i++)
1677             {
1678                 nbs->work[thread].sort_work[i] = -1;
1679             }
1680         }
1681     }
1682
1683     /* Now we know the dimensions we can fill the grid.
1684      * This is the first, unsorted fill. We sort the columns after this.
1685      */
1686     for (i = a0; i < a1; i++)
1687     {
1688         /* At this point nbs->cell contains the local grid x,y indices */
1689         cxy = nbs->cell[i];
1690         nbs->a[(grid->cell0 + grid->cxy_ind[cxy])*grid->na_sc + grid->cxy_na[cxy]++] = i;
1691     }
1692
1693     if (dd_zone == 0)
1694     {
1695         /* Set the cell indices for the moved particles */
1696         n0 = grid->nc*grid->na_sc;
1697         n1 = grid->nc*grid->na_sc+grid->cxy_na[grid->ncx*grid->ncy];
1698         if (dd_zone == 0)
1699         {
1700             for (i = n0; i < n1; i++)
1701             {
1702                 nbs->cell[nbs->a[i]] = i;
1703             }
1704         }
1705     }
1706
1707     /* Sort the super-cell columns along z into the sub-cells. */
1708 #pragma omp parallel for num_threads(nthread) schedule(static)
1709     for (thread = 0; thread < nthread; thread++)
1710     {
1711         if (grid->bSimple)
1712         {
1713             sort_columns_simple(nbs, dd_zone, grid, a0, a1, atinfo, x, nbat,
1714                                 ((thread+0)*grid->ncx*grid->ncy)/nthread,
1715                                 ((thread+1)*grid->ncx*grid->ncy)/nthread,
1716                                 nbs->work[thread].sort_work);
1717         }
1718         else
1719         {
1720             sort_columns_supersub(nbs, dd_zone, grid, a0, a1, atinfo, x, nbat,
1721                                   ((thread+0)*grid->ncx*grid->ncy)/nthread,
1722                                   ((thread+1)*grid->ncx*grid->ncy)/nthread,
1723                                   nbs->work[thread].sort_work);
1724         }
1725     }
1726
1727     if (grid->bSimple && nbat->XFormat == nbatX8)
1728     {
1729         combine_bounding_box_pairs(grid, grid->bb);
1730     }
1731
1732     if (!grid->bSimple)
1733     {
1734         grid->nsubc_tot = 0;
1735         for (i = 0; i < grid->nc; i++)
1736         {
1737             grid->nsubc_tot += grid->nsubc[i];
1738         }
1739     }
1740
1741     if (debug)
1742     {
1743         if (grid->bSimple)
1744         {
1745             print_bbsizes_simple(debug, nbs, grid);
1746         }
1747         else
1748         {
1749             fprintf(debug, "ns non-zero sub-cells: %d average atoms %.2f\n",
1750                     grid->nsubc_tot, (a1-a0)/(double)grid->nsubc_tot);
1751
1752             print_bbsizes_supersub(debug, nbs, grid);
1753         }
1754     }
1755 }
1756
1757 static void init_buffer_flags(nbnxn_buffer_flags_t *flags,
1758                               int                   natoms)
1759 {
1760     int b;
1761
1762     flags->nflag = (natoms + NBNXN_BUFFERFLAG_SIZE - 1)/NBNXN_BUFFERFLAG_SIZE;
1763     if (flags->nflag > flags->flag_nalloc)
1764     {
1765         flags->flag_nalloc = over_alloc_large(flags->nflag);
1766         srenew(flags->flag, flags->flag_nalloc);
1767     }
1768     for (b = 0; b < flags->nflag; b++)
1769     {
1770         flags->flag[b] = 0;
1771     }
1772 }
1773
1774 /* Sets up a grid and puts the atoms on the grid.
1775  * This function only operates on one domain of the domain decompostion.
1776  * Note that without domain decomposition there is only one domain.
1777  */
1778 void nbnxn_put_on_grid(nbnxn_search_t nbs,
1779                        int ePBC, matrix box,
1780                        int dd_zone,
1781                        rvec corner0, rvec corner1,
1782                        int a0, int a1,
1783                        real atom_density,
1784                        const int *atinfo,
1785                        rvec *x,
1786                        int nmoved, int *move,
1787                        int nb_kernel_type,
1788                        nbnxn_atomdata_t *nbat)
1789 {
1790     nbnxn_grid_t *grid;
1791     int           n;
1792     int           nc_max_grid, nc_max;
1793
1794     grid = &nbs->grid[dd_zone];
1795
1796     nbs_cycle_start(&nbs->cc[enbsCCgrid]);
1797
1798     grid->bSimple = nbnxn_kernel_pairlist_simple(nb_kernel_type);
1799
1800     grid->na_c      = nbnxn_kernel_to_ci_size(nb_kernel_type);
1801     grid->na_cj     = nbnxn_kernel_to_cj_size(nb_kernel_type);
1802     grid->na_sc     = (grid->bSimple ? 1 : GPU_NSUBCELL)*grid->na_c;
1803     grid->na_c_2log = get_2log(grid->na_c);
1804
1805     nbat->na_c = grid->na_c;
1806
1807     if (dd_zone == 0)
1808     {
1809         grid->cell0 = 0;
1810     }
1811     else
1812     {
1813         grid->cell0 =
1814             (nbs->grid[dd_zone-1].cell0 + nbs->grid[dd_zone-1].nc)*
1815             nbs->grid[dd_zone-1].na_sc/grid->na_sc;
1816     }
1817
1818     n = a1 - a0;
1819
1820     if (dd_zone == 0)
1821     {
1822         nbs->ePBC = ePBC;
1823         copy_mat(box, nbs->box);
1824
1825         /* Avoid zero density */
1826         if (atom_density > 0)
1827         {
1828             grid->atom_density = atom_density;
1829         }
1830         else
1831         {
1832             grid->atom_density = grid_atom_density(n-nmoved, corner0, corner1);
1833         }
1834
1835         grid->cell0 = 0;
1836
1837         nbs->natoms_local    = a1 - nmoved;
1838         /* We assume that nbnxn_put_on_grid is called first
1839          * for the local atoms (dd_zone=0).
1840          */
1841         nbs->natoms_nonlocal = a1 - nmoved;
1842
1843         if (debug)
1844         {
1845             fprintf(debug, "natoms_local = %5d atom_density = %5.1f\n",
1846                     nbs->natoms_local, grid->atom_density);
1847         }
1848     }
1849     else
1850     {
1851         nbs->natoms_nonlocal = max(nbs->natoms_nonlocal, a1);
1852     }
1853
1854     /* We always use the home zone (grid[0]) for setting the cell size,
1855      * since determining densities for non-local zones is difficult.
1856      */
1857     nc_max_grid = set_grid_size_xy(nbs, grid,
1858                                    dd_zone, n-nmoved, corner0, corner1,
1859                                    nbs->grid[0].atom_density);
1860
1861     nc_max = grid->cell0 + nc_max_grid;
1862
1863     if (a1 > nbs->cell_nalloc)
1864     {
1865         nbs->cell_nalloc = over_alloc_large(a1);
1866         srenew(nbs->cell, nbs->cell_nalloc);
1867     }
1868
1869     /* To avoid conditionals we store the moved particles at the end of a,
1870      * make sure we have enough space.
1871      */
1872     if (nc_max*grid->na_sc + nmoved > nbs->a_nalloc)
1873     {
1874         nbs->a_nalloc = over_alloc_large(nc_max*grid->na_sc + nmoved);
1875         srenew(nbs->a, nbs->a_nalloc);
1876     }
1877
1878     /* We need padding up to a multiple of the buffer flag size: simply add */
1879     if (nc_max*grid->na_sc + NBNXN_BUFFERFLAG_SIZE > nbat->nalloc)
1880     {
1881         nbnxn_atomdata_realloc(nbat, nc_max*grid->na_sc+NBNXN_BUFFERFLAG_SIZE);
1882     }
1883
1884     calc_cell_indices(nbs, dd_zone, grid, a0, a1, atinfo, x, move, nbat);
1885
1886     if (dd_zone == 0)
1887     {
1888         nbat->natoms_local = nbat->natoms;
1889     }
1890
1891     nbs_cycle_stop(&nbs->cc[enbsCCgrid]);
1892 }
1893
1894 /* Calls nbnxn_put_on_grid for all non-local domains */
1895 void nbnxn_put_on_grid_nonlocal(nbnxn_search_t            nbs,
1896                                 const gmx_domdec_zones_t *zones,
1897                                 const int                *atinfo,
1898                                 rvec                     *x,
1899                                 int                       nb_kernel_type,
1900                                 nbnxn_atomdata_t         *nbat)
1901 {
1902     int  zone, d;
1903     rvec c0, c1;
1904
1905     for (zone = 1; zone < zones->n; zone++)
1906     {
1907         for (d = 0; d < DIM; d++)
1908         {
1909             c0[d] = zones->size[zone].bb_x0[d];
1910             c1[d] = zones->size[zone].bb_x1[d];
1911         }
1912
1913         nbnxn_put_on_grid(nbs, nbs->ePBC, NULL,
1914                           zone, c0, c1,
1915                           zones->cg_range[zone],
1916                           zones->cg_range[zone+1],
1917                           -1,
1918                           atinfo,
1919                           x,
1920                           0, NULL,
1921                           nb_kernel_type,
1922                           nbat);
1923     }
1924 }
1925
1926 /* Add simple grid type information to the local super/sub grid */
1927 void nbnxn_grid_add_simple(nbnxn_search_t    nbs,
1928                            nbnxn_atomdata_t *nbat)
1929 {
1930     nbnxn_grid_t *grid;
1931     float        *bbcz;
1932     nbnxn_bb_t   *bb;
1933     int           ncd, sc;
1934
1935     grid = &nbs->grid[0];
1936
1937     if (grid->bSimple)
1938     {
1939         gmx_incons("nbnxn_grid_simple called with a simple grid");
1940     }
1941
1942     ncd = grid->na_sc/NBNXN_CPU_CLUSTER_I_SIZE;
1943
1944     if (grid->nc*ncd > grid->nc_nalloc_simple)
1945     {
1946         grid->nc_nalloc_simple = over_alloc_large(grid->nc*ncd);
1947         srenew(grid->bbcz_simple, grid->nc_nalloc_simple*NNBSBB_D);
1948         srenew(grid->bb_simple, grid->nc_nalloc_simple);
1949         srenew(grid->flags_simple, grid->nc_nalloc_simple);
1950         if (nbat->XFormat)
1951         {
1952             sfree_aligned(grid->bbj);
1953             snew_aligned(grid->bbj, grid->nc_nalloc_simple/2, 16);
1954         }
1955     }
1956
1957     bbcz = grid->bbcz_simple;
1958     bb   = grid->bb_simple;
1959
1960 #pragma omp parallel for num_threads(gmx_omp_nthreads_get(emntPairsearch)) schedule(static)
1961     for (sc = 0; sc < grid->nc; sc++)
1962     {
1963         int c, tx, na;
1964
1965         for (c = 0; c < ncd; c++)
1966         {
1967             tx = sc*ncd + c;
1968
1969             na = NBNXN_CPU_CLUSTER_I_SIZE;
1970             while (na > 0 &&
1971                    nbat->type[tx*NBNXN_CPU_CLUSTER_I_SIZE+na-1] == nbat->ntype-1)
1972             {
1973                 na--;
1974             }
1975
1976             if (na > 0)
1977             {
1978                 switch (nbat->XFormat)
1979                 {
1980                     case nbatX4:
1981                         /* PACK_X4==NBNXN_CPU_CLUSTER_I_SIZE, so this is simple */
1982                         calc_bounding_box_x_x4(na, nbat->x+tx*STRIDE_P4,
1983                                                bb+tx);
1984                         break;
1985                     case nbatX8:
1986                         /* PACK_X8>NBNXN_CPU_CLUSTER_I_SIZE, more complicated */
1987                         calc_bounding_box_x_x8(na, nbat->x+X8_IND_A(tx*NBNXN_CPU_CLUSTER_I_SIZE),
1988                                                bb+tx);
1989                         break;
1990                     default:
1991                         calc_bounding_box(na, nbat->xstride,
1992                                           nbat->x+tx*NBNXN_CPU_CLUSTER_I_SIZE*nbat->xstride,
1993                                           bb+tx);
1994                         break;
1995                 }
1996                 bbcz[tx*NNBSBB_D+0] = bb[tx].lower[BB_Z];
1997                 bbcz[tx*NNBSBB_D+1] = bb[tx].upper[BB_Z];
1998
1999                 /* No interaction optimization yet here */
2000                 grid->flags_simple[tx] = NBNXN_CI_DO_LJ(0) | NBNXN_CI_DO_COUL(0);
2001             }
2002             else
2003             {
2004                 grid->flags_simple[tx] = 0;
2005             }
2006         }
2007     }
2008
2009     if (grid->bSimple && nbat->XFormat == nbatX8)
2010     {
2011         combine_bounding_box_pairs(grid, grid->bb_simple);
2012     }
2013 }
2014
2015 void nbnxn_get_ncells(nbnxn_search_t nbs, int *ncx, int *ncy)
2016 {
2017     *ncx = nbs->grid[0].ncx;
2018     *ncy = nbs->grid[0].ncy;
2019 }
2020
2021 void nbnxn_get_atomorder(nbnxn_search_t nbs, int **a, int *n)
2022 {
2023     const nbnxn_grid_t *grid;
2024
2025     grid = &nbs->grid[0];
2026
2027     /* Return the atom order for the home cell (index 0) */
2028     *a  = nbs->a;
2029
2030     *n = grid->cxy_ind[grid->ncx*grid->ncy]*grid->na_sc;
2031 }
2032
2033 void nbnxn_set_atomorder(nbnxn_search_t nbs)
2034 {
2035     nbnxn_grid_t *grid;
2036     int           ao, cx, cy, cxy, cz, j;
2037
2038     /* Set the atom order for the home cell (index 0) */
2039     grid = &nbs->grid[0];
2040
2041     ao = 0;
2042     for (cx = 0; cx < grid->ncx; cx++)
2043     {
2044         for (cy = 0; cy < grid->ncy; cy++)
2045         {
2046             cxy = cx*grid->ncy + cy;
2047             j   = grid->cxy_ind[cxy]*grid->na_sc;
2048             for (cz = 0; cz < grid->cxy_na[cxy]; cz++)
2049             {
2050                 nbs->a[j]     = ao;
2051                 nbs->cell[ao] = j;
2052                 ao++;
2053                 j++;
2054             }
2055         }
2056     }
2057 }
2058
2059 /* Determines the cell range along one dimension that
2060  * the bounding box b0 - b1 sees.
2061  */
2062 static void get_cell_range(real b0, real b1,
2063                            int nc, real c0, real s, real invs,
2064                            real d2, real r2, int *cf, int *cl)
2065 {
2066     *cf = max((int)((b0 - c0)*invs), 0);
2067
2068     while (*cf > 0 && d2 + sqr((b0 - c0) - (*cf-1+1)*s) < r2)
2069     {
2070         (*cf)--;
2071     }
2072
2073     *cl = min((int)((b1 - c0)*invs), nc-1);
2074     while (*cl < nc-1 && d2 + sqr((*cl+1)*s - (b1 - c0)) < r2)
2075     {
2076         (*cl)++;
2077     }
2078 }
2079
2080 /* Reference code calculating the distance^2 between two bounding boxes */
2081 static float box_dist2(float bx0, float bx1, float by0,
2082                        float by1, float bz0, float bz1,
2083                        const nbnxn_bb_t *bb)
2084 {
2085     float d2;
2086     float dl, dh, dm, dm0;
2087
2088     d2 = 0;
2089
2090     dl  = bx0 - bb->upper[BB_X];
2091     dh  = bb->lower[BB_X] - bx1;
2092     dm  = max(dl, dh);
2093     dm0 = max(dm, 0);
2094     d2 += dm0*dm0;
2095
2096     dl  = by0 - bb->upper[BB_Y];
2097     dh  = bb->lower[BB_Y] - by1;
2098     dm  = max(dl, dh);
2099     dm0 = max(dm, 0);
2100     d2 += dm0*dm0;
2101
2102     dl  = bz0 - bb->upper[BB_Z];
2103     dh  = bb->lower[BB_Z] - bz1;
2104     dm  = max(dl, dh);
2105     dm0 = max(dm, 0);
2106     d2 += dm0*dm0;
2107
2108     return d2;
2109 }
2110
2111 /* Plain C code calculating the distance^2 between two bounding boxes */
2112 static float subc_bb_dist2(int si, const nbnxn_bb_t *bb_i_ci,
2113                            int csj, const nbnxn_bb_t *bb_j_all)
2114 {
2115     const nbnxn_bb_t *bb_i, *bb_j;
2116     float             d2;
2117     float             dl, dh, dm, dm0;
2118
2119     bb_i = bb_i_ci  +  si;
2120     bb_j = bb_j_all + csj;
2121
2122     d2 = 0;
2123
2124     dl  = bb_i->lower[BB_X] - bb_j->upper[BB_X];
2125     dh  = bb_j->lower[BB_X] - bb_i->upper[BB_X];
2126     dm  = max(dl, dh);
2127     dm0 = max(dm, 0);
2128     d2 += dm0*dm0;
2129
2130     dl  = bb_i->lower[BB_Y] - bb_j->upper[BB_Y];
2131     dh  = bb_j->lower[BB_Y] - bb_i->upper[BB_Y];
2132     dm  = max(dl, dh);
2133     dm0 = max(dm, 0);
2134     d2 += dm0*dm0;
2135
2136     dl  = bb_i->lower[BB_Z] - bb_j->upper[BB_Z];
2137     dh  = bb_j->lower[BB_Z] - bb_i->upper[BB_Z];
2138     dm  = max(dl, dh);
2139     dm0 = max(dm, 0);
2140     d2 += dm0*dm0;
2141
2142     return d2;
2143 }
2144
2145 #ifdef NBNXN_SEARCH_BB_SIMD4
2146
2147 /* 4-wide SIMD code for bb distance for bb format xyz0 */
2148 static float subc_bb_dist2_simd4(int si, const nbnxn_bb_t *bb_i_ci,
2149                                  int csj, const nbnxn_bb_t *bb_j_all)
2150 {
2151     gmx_simd4_float_t bb_i_S0, bb_i_S1;
2152     gmx_simd4_float_t bb_j_S0, bb_j_S1;
2153     gmx_simd4_float_t dl_S;
2154     gmx_simd4_float_t dh_S;
2155     gmx_simd4_float_t dm_S;
2156     gmx_simd4_float_t dm0_S;
2157
2158     bb_i_S0 = gmx_simd4_load_f(&bb_i_ci[si].lower[0]);
2159     bb_i_S1 = gmx_simd4_load_f(&bb_i_ci[si].upper[0]);
2160     bb_j_S0 = gmx_simd4_load_f(&bb_j_all[csj].lower[0]);
2161     bb_j_S1 = gmx_simd4_load_f(&bb_j_all[csj].upper[0]);
2162
2163     dl_S    = gmx_simd4_sub_f(bb_i_S0, bb_j_S1);
2164     dh_S    = gmx_simd4_sub_f(bb_j_S0, bb_i_S1);
2165
2166     dm_S    = gmx_simd4_max_f(dl_S, dh_S);
2167     dm0_S   = gmx_simd4_max_f(dm_S, gmx_simd4_setzero_f());
2168
2169     return gmx_simd4_dotproduct3_f(dm0_S, dm0_S);
2170 }
2171
2172 /* Calculate bb bounding distances of bb_i[si,...,si+3] and store them in d2 */
2173 #define SUBC_BB_DIST2_SIMD4_XXXX_INNER(si, bb_i, d2) \
2174     {                                                \
2175         int               shi;                                  \
2176                                                  \
2177         gmx_simd4_float_t dx_0, dy_0, dz_0;                    \
2178         gmx_simd4_float_t dx_1, dy_1, dz_1;                    \
2179                                                  \
2180         gmx_simd4_float_t mx, my, mz;                          \
2181         gmx_simd4_float_t m0x, m0y, m0z;                       \
2182                                                  \
2183         gmx_simd4_float_t d2x, d2y, d2z;                       \
2184         gmx_simd4_float_t d2s, d2t;                            \
2185                                                  \
2186         shi = si*NNBSBB_D*DIM;                       \
2187                                                  \
2188         xi_l = gmx_simd4_load_f(bb_i+shi+0*STRIDE_PBB);   \
2189         yi_l = gmx_simd4_load_f(bb_i+shi+1*STRIDE_PBB);   \
2190         zi_l = gmx_simd4_load_f(bb_i+shi+2*STRIDE_PBB);   \
2191         xi_h = gmx_simd4_load_f(bb_i+shi+3*STRIDE_PBB);   \
2192         yi_h = gmx_simd4_load_f(bb_i+shi+4*STRIDE_PBB);   \
2193         zi_h = gmx_simd4_load_f(bb_i+shi+5*STRIDE_PBB);   \
2194                                                  \
2195         dx_0 = gmx_simd4_sub_f(xi_l, xj_h);                 \
2196         dy_0 = gmx_simd4_sub_f(yi_l, yj_h);                 \
2197         dz_0 = gmx_simd4_sub_f(zi_l, zj_h);                 \
2198                                                  \
2199         dx_1 = gmx_simd4_sub_f(xj_l, xi_h);                 \
2200         dy_1 = gmx_simd4_sub_f(yj_l, yi_h);                 \
2201         dz_1 = gmx_simd4_sub_f(zj_l, zi_h);                 \
2202                                                  \
2203         mx   = gmx_simd4_max_f(dx_0, dx_1);                 \
2204         my   = gmx_simd4_max_f(dy_0, dy_1);                 \
2205         mz   = gmx_simd4_max_f(dz_0, dz_1);                 \
2206                                                  \
2207         m0x  = gmx_simd4_max_f(mx, zero);                   \
2208         m0y  = gmx_simd4_max_f(my, zero);                   \
2209         m0z  = gmx_simd4_max_f(mz, zero);                   \
2210                                                  \
2211         d2x  = gmx_simd4_mul_f(m0x, m0x);                   \
2212         d2y  = gmx_simd4_mul_f(m0y, m0y);                   \
2213         d2z  = gmx_simd4_mul_f(m0z, m0z);                   \
2214                                                  \
2215         d2s  = gmx_simd4_add_f(d2x, d2y);                   \
2216         d2t  = gmx_simd4_add_f(d2s, d2z);                   \
2217                                                  \
2218         gmx_simd4_store_f(d2+si, d2t);                      \
2219     }
2220
2221 /* 4-wide SIMD code for nsi bb distances for bb format xxxxyyyyzzzz */
2222 static void subc_bb_dist2_simd4_xxxx(const float *bb_j,
2223                                      int nsi, const float *bb_i,
2224                                      float *d2)
2225 {
2226     gmx_simd4_float_t xj_l, yj_l, zj_l;
2227     gmx_simd4_float_t xj_h, yj_h, zj_h;
2228     gmx_simd4_float_t xi_l, yi_l, zi_l;
2229     gmx_simd4_float_t xi_h, yi_h, zi_h;
2230
2231     gmx_simd4_float_t zero;
2232
2233     zero = gmx_simd4_setzero_f();
2234
2235     xj_l = gmx_simd4_set1_f(bb_j[0*STRIDE_PBB]);
2236     yj_l = gmx_simd4_set1_f(bb_j[1*STRIDE_PBB]);
2237     zj_l = gmx_simd4_set1_f(bb_j[2*STRIDE_PBB]);
2238     xj_h = gmx_simd4_set1_f(bb_j[3*STRIDE_PBB]);
2239     yj_h = gmx_simd4_set1_f(bb_j[4*STRIDE_PBB]);
2240     zj_h = gmx_simd4_set1_f(bb_j[5*STRIDE_PBB]);
2241
2242     /* Here we "loop" over si (0,STRIDE_PBB) from 0 to nsi with step STRIDE_PBB.
2243      * But as we know the number of iterations is 1 or 2, we unroll manually.
2244      */
2245     SUBC_BB_DIST2_SIMD4_XXXX_INNER(0, bb_i, d2);
2246     if (STRIDE_PBB < nsi)
2247     {
2248         SUBC_BB_DIST2_SIMD4_XXXX_INNER(STRIDE_PBB, bb_i, d2);
2249     }
2250 }
2251
2252 #endif /* NBNXN_SEARCH_BB_SIMD4 */
2253
2254 /* Plain C function which determines if any atom pair between two cells
2255  * is within distance sqrt(rl2).
2256  */
2257 static gmx_bool subc_in_range_x(int na_c,
2258                                 int si, const real *x_i,
2259                                 int csj, int stride, const real *x_j,
2260                                 real rl2)
2261 {
2262     int  i, j, i0, j0;
2263     real d2;
2264
2265     for (i = 0; i < na_c; i++)
2266     {
2267         i0 = (si*na_c + i)*DIM;
2268         for (j = 0; j < na_c; j++)
2269         {
2270             j0 = (csj*na_c + j)*stride;
2271
2272             d2 = sqr(x_i[i0  ] - x_j[j0  ]) +
2273                 sqr(x_i[i0+1] - x_j[j0+1]) +
2274                 sqr(x_i[i0+2] - x_j[j0+2]);
2275
2276             if (d2 < rl2)
2277             {
2278                 return TRUE;
2279             }
2280         }
2281     }
2282
2283     return FALSE;
2284 }
2285
2286 #ifdef NBNXN_SEARCH_SIMD4_FLOAT_X_BB
2287
2288 /* 4-wide SIMD function which determines if any atom pair between two cells,
2289  * both with 8 atoms, is within distance sqrt(rl2).
2290  * Using 8-wide AVX is not faster on Intel Sandy Bridge.
2291  */
2292 static gmx_bool subc_in_range_simd4(int na_c,
2293                                     int si, const real *x_i,
2294                                     int csj, int stride, const real *x_j,
2295                                     real rl2)
2296 {
2297     gmx_simd4_real_t ix_S0, iy_S0, iz_S0;
2298     gmx_simd4_real_t ix_S1, iy_S1, iz_S1;
2299
2300     gmx_simd4_real_t rc2_S;
2301
2302     int              dim_stride;
2303     int              j0, j1;
2304
2305     rc2_S   = gmx_simd4_set1_r(rl2);
2306
2307     dim_stride = NBNXN_GPU_CLUSTER_SIZE/STRIDE_PBB*DIM;
2308     ix_S0      = gmx_simd4_load_r(x_i+(si*dim_stride+0)*STRIDE_PBB);
2309     iy_S0      = gmx_simd4_load_r(x_i+(si*dim_stride+1)*STRIDE_PBB);
2310     iz_S0      = gmx_simd4_load_r(x_i+(si*dim_stride+2)*STRIDE_PBB);
2311     ix_S1      = gmx_simd4_load_r(x_i+(si*dim_stride+3)*STRIDE_PBB);
2312     iy_S1      = gmx_simd4_load_r(x_i+(si*dim_stride+4)*STRIDE_PBB);
2313     iz_S1      = gmx_simd4_load_r(x_i+(si*dim_stride+5)*STRIDE_PBB);
2314
2315     /* We loop from the outer to the inner particles to maximize
2316      * the chance that we find a pair in range quickly and return.
2317      */
2318     j0 = csj*na_c;
2319     j1 = j0 + na_c - 1;
2320     while (j0 < j1)
2321     {
2322         gmx_simd4_real_t jx0_S, jy0_S, jz0_S;
2323         gmx_simd4_real_t jx1_S, jy1_S, jz1_S;
2324
2325         gmx_simd4_real_t dx_S0, dy_S0, dz_S0;
2326         gmx_simd4_real_t dx_S1, dy_S1, dz_S1;
2327         gmx_simd4_real_t dx_S2, dy_S2, dz_S2;
2328         gmx_simd4_real_t dx_S3, dy_S3, dz_S3;
2329
2330         gmx_simd4_real_t rsq_S0;
2331         gmx_simd4_real_t rsq_S1;
2332         gmx_simd4_real_t rsq_S2;
2333         gmx_simd4_real_t rsq_S3;
2334
2335         gmx_simd4_bool_t wco_S0;
2336         gmx_simd4_bool_t wco_S1;
2337         gmx_simd4_bool_t wco_S2;
2338         gmx_simd4_bool_t wco_S3;
2339         gmx_simd4_bool_t wco_any_S01, wco_any_S23, wco_any_S;
2340
2341         jx0_S = gmx_simd4_set1_r(x_j[j0*stride+0]);
2342         jy0_S = gmx_simd4_set1_r(x_j[j0*stride+1]);
2343         jz0_S = gmx_simd4_set1_r(x_j[j0*stride+2]);
2344
2345         jx1_S = gmx_simd4_set1_r(x_j[j1*stride+0]);
2346         jy1_S = gmx_simd4_set1_r(x_j[j1*stride+1]);
2347         jz1_S = gmx_simd4_set1_r(x_j[j1*stride+2]);
2348
2349         /* Calculate distance */
2350         dx_S0            = gmx_simd4_sub_r(ix_S0, jx0_S);
2351         dy_S0            = gmx_simd4_sub_r(iy_S0, jy0_S);
2352         dz_S0            = gmx_simd4_sub_r(iz_S0, jz0_S);
2353         dx_S1            = gmx_simd4_sub_r(ix_S1, jx0_S);
2354         dy_S1            = gmx_simd4_sub_r(iy_S1, jy0_S);
2355         dz_S1            = gmx_simd4_sub_r(iz_S1, jz0_S);
2356         dx_S2            = gmx_simd4_sub_r(ix_S0, jx1_S);
2357         dy_S2            = gmx_simd4_sub_r(iy_S0, jy1_S);
2358         dz_S2            = gmx_simd4_sub_r(iz_S0, jz1_S);
2359         dx_S3            = gmx_simd4_sub_r(ix_S1, jx1_S);
2360         dy_S3            = gmx_simd4_sub_r(iy_S1, jy1_S);
2361         dz_S3            = gmx_simd4_sub_r(iz_S1, jz1_S);
2362
2363         /* rsq = dx*dx+dy*dy+dz*dz */
2364         rsq_S0           = gmx_simd4_calc_rsq_r(dx_S0, dy_S0, dz_S0);
2365         rsq_S1           = gmx_simd4_calc_rsq_r(dx_S1, dy_S1, dz_S1);
2366         rsq_S2           = gmx_simd4_calc_rsq_r(dx_S2, dy_S2, dz_S2);
2367         rsq_S3           = gmx_simd4_calc_rsq_r(dx_S3, dy_S3, dz_S3);
2368
2369         wco_S0           = gmx_simd4_cmplt_r(rsq_S0, rc2_S);
2370         wco_S1           = gmx_simd4_cmplt_r(rsq_S1, rc2_S);
2371         wco_S2           = gmx_simd4_cmplt_r(rsq_S2, rc2_S);
2372         wco_S3           = gmx_simd4_cmplt_r(rsq_S3, rc2_S);
2373
2374         wco_any_S01      = gmx_simd4_or_b(wco_S0, wco_S1);
2375         wco_any_S23      = gmx_simd4_or_b(wco_S2, wco_S3);
2376         wco_any_S        = gmx_simd4_or_b(wco_any_S01, wco_any_S23);
2377
2378         if (gmx_simd4_anytrue_b(wco_any_S))
2379         {
2380             return TRUE;
2381         }
2382
2383         j0++;
2384         j1--;
2385     }
2386     return FALSE;
2387
2388 }
2389 #endif
2390
2391
2392 /* Returns the j sub-cell for index cj_ind */
2393 static int nbl_cj(const nbnxn_pairlist_t *nbl, int cj_ind)
2394 {
2395     return nbl->cj4[cj_ind >> NBNXN_GPU_JGROUP_SIZE_2LOG].cj[cj_ind & (NBNXN_GPU_JGROUP_SIZE - 1)];
2396 }
2397
2398 /* Returns the i-interaction mask of the j sub-cell for index cj_ind */
2399 static unsigned int nbl_imask0(const nbnxn_pairlist_t *nbl, int cj_ind)
2400 {
2401     return nbl->cj4[cj_ind >> NBNXN_GPU_JGROUP_SIZE_2LOG].imei[0].imask;
2402 }
2403
2404 /* Ensures there is enough space for extra extra exclusion masks */
2405 static void check_excl_space(nbnxn_pairlist_t *nbl, int extra)
2406 {
2407     if (nbl->nexcl+extra > nbl->excl_nalloc)
2408     {
2409         nbl->excl_nalloc = over_alloc_small(nbl->nexcl+extra);
2410         nbnxn_realloc_void((void **)&nbl->excl,
2411                            nbl->nexcl*sizeof(*nbl->excl),
2412                            nbl->excl_nalloc*sizeof(*nbl->excl),
2413                            nbl->alloc, nbl->free);
2414     }
2415 }
2416
2417 /* Ensures there is enough space for ncell extra j-cells in the list */
2418 static void check_subcell_list_space_simple(nbnxn_pairlist_t *nbl,
2419                                             int               ncell)
2420 {
2421     int cj_max;
2422
2423     cj_max = nbl->ncj + ncell;
2424
2425     if (cj_max > nbl->cj_nalloc)
2426     {
2427         nbl->cj_nalloc = over_alloc_small(cj_max);
2428         nbnxn_realloc_void((void **)&nbl->cj,
2429                            nbl->ncj*sizeof(*nbl->cj),
2430                            nbl->cj_nalloc*sizeof(*nbl->cj),
2431                            nbl->alloc, nbl->free);
2432     }
2433 }
2434
2435 /* Ensures there is enough space for ncell extra j-subcells in the list */
2436 static void check_subcell_list_space_supersub(nbnxn_pairlist_t *nbl,
2437                                               int               nsupercell)
2438 {
2439     int ncj4_max, j4, j, w, t;
2440
2441 #define NWARP       2
2442 #define WARP_SIZE  32
2443
2444     /* We can have maximally nsupercell*GPU_NSUBCELL sj lists */
2445     /* We can store 4 j-subcell - i-supercell pairs in one struct.
2446      * since we round down, we need one extra entry.
2447      */
2448     ncj4_max = ((nbl->work->cj_ind + nsupercell*GPU_NSUBCELL + NBNXN_GPU_JGROUP_SIZE - 1) >> NBNXN_GPU_JGROUP_SIZE_2LOG);
2449
2450     if (ncj4_max > nbl->cj4_nalloc)
2451     {
2452         nbl->cj4_nalloc = over_alloc_small(ncj4_max);
2453         nbnxn_realloc_void((void **)&nbl->cj4,
2454                            nbl->work->cj4_init*sizeof(*nbl->cj4),
2455                            nbl->cj4_nalloc*sizeof(*nbl->cj4),
2456                            nbl->alloc, nbl->free);
2457     }
2458
2459     if (ncj4_max > nbl->work->cj4_init)
2460     {
2461         for (j4 = nbl->work->cj4_init; j4 < ncj4_max; j4++)
2462         {
2463             /* No i-subcells and no excl's in the list initially */
2464             for (w = 0; w < NWARP; w++)
2465             {
2466                 nbl->cj4[j4].imei[w].imask    = 0U;
2467                 nbl->cj4[j4].imei[w].excl_ind = 0;
2468
2469             }
2470         }
2471         nbl->work->cj4_init = ncj4_max;
2472     }
2473 }
2474
2475 /* Set all excl masks for one GPU warp no exclusions */
2476 static void set_no_excls(nbnxn_excl_t *excl)
2477 {
2478     int t;
2479
2480     for (t = 0; t < WARP_SIZE; t++)
2481     {
2482         /* Turn all interaction bits on */
2483         excl->pair[t] = NBNXN_INTERACTION_MASK_ALL;
2484     }
2485 }
2486
2487 /* Initializes a single nbnxn_pairlist_t data structure */
2488 static void nbnxn_init_pairlist(nbnxn_pairlist_t *nbl,
2489                                 gmx_bool          bSimple,
2490                                 nbnxn_alloc_t    *alloc,
2491                                 nbnxn_free_t     *free)
2492 {
2493     if (alloc == NULL)
2494     {
2495         nbl->alloc = nbnxn_alloc_aligned;
2496     }
2497     else
2498     {
2499         nbl->alloc = alloc;
2500     }
2501     if (free == NULL)
2502     {
2503         nbl->free = nbnxn_free_aligned;
2504     }
2505     else
2506     {
2507         nbl->free = free;
2508     }
2509
2510     nbl->bSimple     = bSimple;
2511     nbl->na_sc       = 0;
2512     nbl->na_ci       = 0;
2513     nbl->na_cj       = 0;
2514     nbl->nci         = 0;
2515     nbl->ci          = NULL;
2516     nbl->ci_nalloc   = 0;
2517     nbl->ncj         = 0;
2518     nbl->cj          = NULL;
2519     nbl->cj_nalloc   = 0;
2520     nbl->ncj4        = 0;
2521     /* We need one element extra in sj, so alloc initially with 1 */
2522     nbl->cj4_nalloc  = 0;
2523     nbl->cj4         = NULL;
2524     nbl->nci_tot     = 0;
2525
2526     if (!nbl->bSimple)
2527     {
2528         nbl->excl        = NULL;
2529         nbl->excl_nalloc = 0;
2530         nbl->nexcl       = 0;
2531         check_excl_space(nbl, 1);
2532         nbl->nexcl       = 1;
2533         set_no_excls(&nbl->excl[0]);
2534     }
2535
2536     snew(nbl->work, 1);
2537     if (nbl->bSimple)
2538     {
2539         snew_aligned(nbl->work->bb_ci, 1, NBNXN_SEARCH_BB_MEM_ALIGN);
2540     }
2541     else
2542     {
2543 #ifdef NBNXN_BBXXXX
2544         snew_aligned(nbl->work->pbb_ci, GPU_NSUBCELL/STRIDE_PBB*NNBSBB_XXXX, NBNXN_SEARCH_BB_MEM_ALIGN);
2545 #else
2546         snew_aligned(nbl->work->bb_ci, GPU_NSUBCELL, NBNXN_SEARCH_BB_MEM_ALIGN);
2547 #endif
2548     }
2549     snew_aligned(nbl->work->x_ci, NBNXN_NA_SC_MAX*DIM, NBNXN_SEARCH_BB_MEM_ALIGN);
2550 #ifdef GMX_NBNXN_SIMD
2551     snew_aligned(nbl->work->x_ci_simd_4xn, 1, NBNXN_MEM_ALIGN);
2552     snew_aligned(nbl->work->x_ci_simd_2xnn, 1, NBNXN_MEM_ALIGN);
2553 #endif
2554     snew_aligned(nbl->work->d2, GPU_NSUBCELL, NBNXN_SEARCH_BB_MEM_ALIGN);
2555
2556     nbl->work->sort            = NULL;
2557     nbl->work->sort_nalloc     = 0;
2558     nbl->work->sci_sort        = NULL;
2559     nbl->work->sci_sort_nalloc = 0;
2560 }
2561
2562 void nbnxn_init_pairlist_set(nbnxn_pairlist_set_t *nbl_list,
2563                              gmx_bool bSimple, gmx_bool bCombined,
2564                              nbnxn_alloc_t *alloc,
2565                              nbnxn_free_t  *free)
2566 {
2567     int i;
2568
2569     nbl_list->bSimple   = bSimple;
2570     nbl_list->bCombined = bCombined;
2571
2572     nbl_list->nnbl = gmx_omp_nthreads_get(emntNonbonded);
2573
2574     if (!nbl_list->bCombined &&
2575         nbl_list->nnbl > NBNXN_BUFFERFLAG_MAX_THREADS)
2576     {
2577         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.",
2578                   nbl_list->nnbl, NBNXN_BUFFERFLAG_MAX_THREADS, NBNXN_BUFFERFLAG_MAX_THREADS);
2579     }
2580
2581     snew(nbl_list->nbl, nbl_list->nnbl);
2582     snew(nbl_list->nbl_fep, nbl_list->nnbl);
2583     /* Execute in order to avoid memory interleaving between threads */
2584 #pragma omp parallel for num_threads(nbl_list->nnbl) schedule(static)
2585     for (i = 0; i < nbl_list->nnbl; i++)
2586     {
2587         /* Allocate the nblist data structure locally on each thread
2588          * to optimize memory access for NUMA architectures.
2589          */
2590         snew(nbl_list->nbl[i], 1);
2591
2592         /* Only list 0 is used on the GPU, use normal allocation for i>0 */
2593         if (i == 0)
2594         {
2595             nbnxn_init_pairlist(nbl_list->nbl[i], nbl_list->bSimple, alloc, free);
2596         }
2597         else
2598         {
2599             nbnxn_init_pairlist(nbl_list->nbl[i], nbl_list->bSimple, NULL, NULL);
2600         }
2601
2602         snew(nbl_list->nbl_fep[i], 1);
2603         nbnxn_init_pairlist_fep(nbl_list->nbl_fep[i]);
2604     }
2605 }
2606
2607 /* Print statistics of a pair list, used for debug output */
2608 static void print_nblist_statistics_simple(FILE *fp, const nbnxn_pairlist_t *nbl,
2609                                            const nbnxn_search_t nbs, real rl)
2610 {
2611     const nbnxn_grid_t *grid;
2612     int                 cs[SHIFTS];
2613     int                 s, i, j;
2614     int                 npexcl;
2615
2616     /* This code only produces correct statistics with domain decomposition */
2617     grid = &nbs->grid[0];
2618
2619     fprintf(fp, "nbl nci %d ncj %d\n",
2620             nbl->nci, nbl->ncj);
2621     fprintf(fp, "nbl na_sc %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n",
2622             nbl->na_sc, rl, nbl->ncj, nbl->ncj/(double)grid->nc,
2623             nbl->ncj/(double)grid->nc*grid->na_sc,
2624             nbl->ncj/(double)grid->nc*grid->na_sc/(0.5*4.0/3.0*M_PI*rl*rl*rl*grid->nc*grid->na_sc/det(nbs->box)));
2625
2626     fprintf(fp, "nbl average j cell list length %.1f\n",
2627             0.25*nbl->ncj/(double)nbl->nci);
2628
2629     for (s = 0; s < SHIFTS; s++)
2630     {
2631         cs[s] = 0;
2632     }
2633     npexcl = 0;
2634     for (i = 0; i < nbl->nci; i++)
2635     {
2636         cs[nbl->ci[i].shift & NBNXN_CI_SHIFT] +=
2637             nbl->ci[i].cj_ind_end - nbl->ci[i].cj_ind_start;
2638
2639         j = nbl->ci[i].cj_ind_start;
2640         while (j < nbl->ci[i].cj_ind_end &&
2641                nbl->cj[j].excl != NBNXN_INTERACTION_MASK_ALL)
2642         {
2643             npexcl++;
2644             j++;
2645         }
2646     }
2647     fprintf(fp, "nbl cell pairs, total: %d excl: %d %.1f%%\n",
2648             nbl->ncj, npexcl, 100*npexcl/(double)nbl->ncj);
2649     for (s = 0; s < SHIFTS; s++)
2650     {
2651         if (cs[s] > 0)
2652         {
2653             fprintf(fp, "nbl shift %2d ncj %3d\n", s, cs[s]);
2654         }
2655     }
2656 }
2657
2658 /* Print statistics of a pair lists, used for debug output */
2659 static void print_nblist_statistics_supersub(FILE *fp, const nbnxn_pairlist_t *nbl,
2660                                              const nbnxn_search_t nbs, real rl)
2661 {
2662     const nbnxn_grid_t *grid;
2663     int                 i, j4, j, si, b;
2664     int                 c[GPU_NSUBCELL+1];
2665
2666     /* This code only produces correct statistics with domain decomposition */
2667     grid = &nbs->grid[0];
2668
2669     fprintf(fp, "nbl nsci %d ncj4 %d nsi %d excl4 %d\n",
2670             nbl->nsci, nbl->ncj4, nbl->nci_tot, nbl->nexcl);
2671     fprintf(fp, "nbl na_c %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n",
2672             nbl->na_ci, rl, nbl->nci_tot, nbl->nci_tot/(double)grid->nsubc_tot,
2673             nbl->nci_tot/(double)grid->nsubc_tot*grid->na_c,
2674             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/det(nbs->box)));
2675
2676     fprintf(fp, "nbl average j super cell list length %.1f\n",
2677             0.25*nbl->ncj4/(double)nbl->nsci);
2678     fprintf(fp, "nbl average i sub cell list length %.1f\n",
2679             nbl->nci_tot/((double)nbl->ncj4));
2680
2681     for (si = 0; si <= GPU_NSUBCELL; si++)
2682     {
2683         c[si] = 0;
2684     }
2685     for (i = 0; i < nbl->nsci; i++)
2686     {
2687         for (j4 = nbl->sci[i].cj4_ind_start; j4 < nbl->sci[i].cj4_ind_end; j4++)
2688         {
2689             for (j = 0; j < NBNXN_GPU_JGROUP_SIZE; j++)
2690             {
2691                 b = 0;
2692                 for (si = 0; si < GPU_NSUBCELL; si++)
2693                 {
2694                     if (nbl->cj4[j4].imei[0].imask & (1U << (j*GPU_NSUBCELL + si)))
2695                     {
2696                         b++;
2697                     }
2698                 }
2699                 c[b]++;
2700             }
2701         }
2702     }
2703     for (b = 0; b <= GPU_NSUBCELL; b++)
2704     {
2705         fprintf(fp, "nbl j-list #i-subcell %d %7d %4.1f\n",
2706                 b, c[b], 100.0*c[b]/(double)(nbl->ncj4*NBNXN_GPU_JGROUP_SIZE));
2707     }
2708 }
2709
2710 /* Returns a pointer to the exclusion mask for cj4-unit cj4, warp warp */
2711 static void low_get_nbl_exclusions(nbnxn_pairlist_t *nbl, int cj4,
2712                                    int warp, nbnxn_excl_t **excl)
2713 {
2714     if (nbl->cj4[cj4].imei[warp].excl_ind == 0)
2715     {
2716         /* No exclusions set, make a new list entry */
2717         nbl->cj4[cj4].imei[warp].excl_ind = nbl->nexcl;
2718         nbl->nexcl++;
2719         *excl = &nbl->excl[nbl->cj4[cj4].imei[warp].excl_ind];
2720         set_no_excls(*excl);
2721     }
2722     else
2723     {
2724         /* We already have some exclusions, new ones can be added to the list */
2725         *excl = &nbl->excl[nbl->cj4[cj4].imei[warp].excl_ind];
2726     }
2727 }
2728
2729 /* Returns a pointer to the exclusion mask for cj4-unit cj4, warp warp,
2730  * generates a new element and allocates extra memory, if necessary.
2731  */
2732 static void get_nbl_exclusions_1(nbnxn_pairlist_t *nbl, int cj4,
2733                                  int warp, nbnxn_excl_t **excl)
2734 {
2735     if (nbl->cj4[cj4].imei[warp].excl_ind == 0)
2736     {
2737         /* We need to make a new list entry, check if we have space */
2738         check_excl_space(nbl, 1);
2739     }
2740     low_get_nbl_exclusions(nbl, cj4, warp, excl);
2741 }
2742
2743 /* Returns pointers to the exclusion mask for cj4-unit cj4 for both warps,
2744  * generates a new element and allocates extra memory, if necessary.
2745  */
2746 static void get_nbl_exclusions_2(nbnxn_pairlist_t *nbl, int cj4,
2747                                  nbnxn_excl_t **excl_w0,
2748                                  nbnxn_excl_t **excl_w1)
2749 {
2750     /* Check for space we might need */
2751     check_excl_space(nbl, 2);
2752
2753     low_get_nbl_exclusions(nbl, cj4, 0, excl_w0);
2754     low_get_nbl_exclusions(nbl, cj4, 1, excl_w1);
2755 }
2756
2757 /* Sets the self exclusions i=j and pair exclusions i>j */
2758 static void set_self_and_newton_excls_supersub(nbnxn_pairlist_t *nbl,
2759                                                int cj4_ind, int sj_offset,
2760                                                int si)
2761 {
2762     nbnxn_excl_t *excl[2];
2763     int           ei, ej, w;
2764
2765     /* Here we only set the set self and double pair exclusions */
2766
2767     get_nbl_exclusions_2(nbl, cj4_ind, &excl[0], &excl[1]);
2768
2769     /* Only minor < major bits set */
2770     for (ej = 0; ej < nbl->na_ci; ej++)
2771     {
2772         w = (ej>>2);
2773         for (ei = ej; ei < nbl->na_ci; ei++)
2774         {
2775             excl[w]->pair[(ej & (NBNXN_GPU_JGROUP_SIZE-1))*nbl->na_ci + ei] &=
2776                 ~(1U << (sj_offset*GPU_NSUBCELL + si));
2777         }
2778     }
2779 }
2780
2781 /* Returns a diagonal or off-diagonal interaction mask for plain C lists */
2782 static unsigned int get_imask(gmx_bool rdiag, int ci, int cj)
2783 {
2784     return (rdiag && ci == cj ? NBNXN_INTERACTION_MASK_DIAG : NBNXN_INTERACTION_MASK_ALL);
2785 }
2786
2787 /* Returns a diagonal or off-diagonal interaction mask for cj-size=2 */
2788 static unsigned int get_imask_simd_j2(gmx_bool rdiag, int ci, int cj)
2789 {
2790     return (rdiag && ci*2 == cj ? NBNXN_INTERACTION_MASK_DIAG_J2_0 :
2791             (rdiag && ci*2+1 == cj ? NBNXN_INTERACTION_MASK_DIAG_J2_1 :
2792              NBNXN_INTERACTION_MASK_ALL));
2793 }
2794
2795 /* Returns a diagonal or off-diagonal interaction mask for cj-size=4 */
2796 static unsigned int get_imask_simd_j4(gmx_bool rdiag, int ci, int cj)
2797 {
2798     return (rdiag && ci == cj ? NBNXN_INTERACTION_MASK_DIAG : NBNXN_INTERACTION_MASK_ALL);
2799 }
2800
2801 /* Returns a diagonal or off-diagonal interaction mask for cj-size=8 */
2802 static unsigned int get_imask_simd_j8(gmx_bool rdiag, int ci, int cj)
2803 {
2804     return (rdiag && ci == cj*2 ? NBNXN_INTERACTION_MASK_DIAG_J8_0 :
2805             (rdiag && ci == cj*2+1 ? NBNXN_INTERACTION_MASK_DIAG_J8_1 :
2806              NBNXN_INTERACTION_MASK_ALL));
2807 }
2808
2809 #ifdef GMX_NBNXN_SIMD
2810 #if GMX_SIMD_REAL_WIDTH == 2
2811 #define get_imask_simd_4xn  get_imask_simd_j2
2812 #endif
2813 #if GMX_SIMD_REAL_WIDTH == 4
2814 #define get_imask_simd_4xn  get_imask_simd_j4
2815 #endif
2816 #if GMX_SIMD_REAL_WIDTH == 8
2817 #define get_imask_simd_4xn  get_imask_simd_j8
2818 #define get_imask_simd_2xnn get_imask_simd_j4
2819 #endif
2820 #if GMX_SIMD_REAL_WIDTH == 16
2821 #define get_imask_simd_2xnn get_imask_simd_j8
2822 #endif
2823 #endif
2824
2825 /* Plain C code for making a pair list of cell ci vs cell cjf-cjl.
2826  * Checks bounding box distances and possibly atom pair distances.
2827  */
2828 static void make_cluster_list_simple(const nbnxn_grid_t *gridj,
2829                                      nbnxn_pairlist_t *nbl,
2830                                      int ci, int cjf, int cjl,
2831                                      gmx_bool remove_sub_diag,
2832                                      const real *x_j,
2833                                      real rl2, float rbb2,
2834                                      int *ndistc)
2835 {
2836     const nbnxn_list_work_t *work;
2837
2838     const nbnxn_bb_t        *bb_ci;
2839     const real              *x_ci;
2840
2841     gmx_bool                 InRange;
2842     real                     d2;
2843     int                      cjf_gl, cjl_gl, cj;
2844
2845     work = nbl->work;
2846
2847     bb_ci = nbl->work->bb_ci;
2848     x_ci  = nbl->work->x_ci;
2849
2850     InRange = FALSE;
2851     while (!InRange && cjf <= cjl)
2852     {
2853         d2       = subc_bb_dist2(0, bb_ci, cjf, gridj->bb);
2854         *ndistc += 2;
2855
2856         /* Check if the distance is within the distance where
2857          * we use only the bounding box distance rbb,
2858          * or within the cut-off and there is at least one atom pair
2859          * within the cut-off.
2860          */
2861         if (d2 < rbb2)
2862         {
2863             InRange = TRUE;
2864         }
2865         else if (d2 < rl2)
2866         {
2867             int i, j;
2868
2869             cjf_gl = gridj->cell0 + cjf;
2870             for (i = 0; i < NBNXN_CPU_CLUSTER_I_SIZE && !InRange; i++)
2871             {
2872                 for (j = 0; j < NBNXN_CPU_CLUSTER_I_SIZE; j++)
2873                 {
2874                     InRange = InRange ||
2875                         (sqr(x_ci[i*STRIDE_XYZ+XX] - x_j[(cjf_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+XX]) +
2876                          sqr(x_ci[i*STRIDE_XYZ+YY] - x_j[(cjf_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+YY]) +
2877                          sqr(x_ci[i*STRIDE_XYZ+ZZ] - x_j[(cjf_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+ZZ]) < rl2);
2878                 }
2879             }
2880             *ndistc += NBNXN_CPU_CLUSTER_I_SIZE*NBNXN_CPU_CLUSTER_I_SIZE;
2881         }
2882         if (!InRange)
2883         {
2884             cjf++;
2885         }
2886     }
2887     if (!InRange)
2888     {
2889         return;
2890     }
2891
2892     InRange = FALSE;
2893     while (!InRange && cjl > cjf)
2894     {
2895         d2       = subc_bb_dist2(0, bb_ci, cjl, gridj->bb);
2896         *ndistc += 2;
2897
2898         /* Check if the distance is within the distance where
2899          * we use only the bounding box distance rbb,
2900          * or within the cut-off and there is at least one atom pair
2901          * within the cut-off.
2902          */
2903         if (d2 < rbb2)
2904         {
2905             InRange = TRUE;
2906         }
2907         else if (d2 < rl2)
2908         {
2909             int i, j;
2910
2911             cjl_gl = gridj->cell0 + cjl;
2912             for (i = 0; i < NBNXN_CPU_CLUSTER_I_SIZE && !InRange; i++)
2913             {
2914                 for (j = 0; j < NBNXN_CPU_CLUSTER_I_SIZE; j++)
2915                 {
2916                     InRange = InRange ||
2917                         (sqr(x_ci[i*STRIDE_XYZ+XX] - x_j[(cjl_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+XX]) +
2918                          sqr(x_ci[i*STRIDE_XYZ+YY] - x_j[(cjl_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+YY]) +
2919                          sqr(x_ci[i*STRIDE_XYZ+ZZ] - x_j[(cjl_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+ZZ]) < rl2);
2920                 }
2921             }
2922             *ndistc += NBNXN_CPU_CLUSTER_I_SIZE*NBNXN_CPU_CLUSTER_I_SIZE;
2923         }
2924         if (!InRange)
2925         {
2926             cjl--;
2927         }
2928     }
2929
2930     if (cjf <= cjl)
2931     {
2932         for (cj = cjf; cj <= cjl; cj++)
2933         {
2934             /* Store cj and the interaction mask */
2935             nbl->cj[nbl->ncj].cj   = gridj->cell0 + cj;
2936             nbl->cj[nbl->ncj].excl = get_imask(remove_sub_diag, ci, cj);
2937             nbl->ncj++;
2938         }
2939         /* Increase the closing index in i super-cell list */
2940         nbl->ci[nbl->nci].cj_ind_end = nbl->ncj;
2941     }
2942 }
2943
2944 #ifdef GMX_NBNXN_SIMD_4XN
2945 #include "gromacs/mdlib/nbnxn_search_simd_4xn.h"
2946 #endif
2947 #ifdef GMX_NBNXN_SIMD_2XNN
2948 #include "gromacs/mdlib/nbnxn_search_simd_2xnn.h"
2949 #endif
2950
2951 /* Plain C or SIMD4 code for making a pair list of super-cell sci vs scj.
2952  * Checks bounding box distances and possibly atom pair distances.
2953  */
2954 static void make_cluster_list_supersub(const nbnxn_grid_t *gridi,
2955                                        const nbnxn_grid_t *gridj,
2956                                        nbnxn_pairlist_t *nbl,
2957                                        int sci, int scj,
2958                                        gmx_bool sci_equals_scj,
2959                                        int stride, const real *x,
2960                                        real rl2, float rbb2,
2961                                        int *ndistc)
2962 {
2963     int               na_c;
2964     int               npair;
2965     int               cjo, ci1, ci, cj, cj_gl;
2966     int               cj4_ind, cj_offset;
2967     unsigned int      imask;
2968     nbnxn_cj4_t      *cj4;
2969 #ifdef NBNXN_BBXXXX
2970     const float      *pbb_ci;
2971 #else
2972     const nbnxn_bb_t *bb_ci;
2973 #endif
2974     const real       *x_ci;
2975     float            *d2l, d2;
2976     int               w;
2977 #define PRUNE_LIST_CPU_ONE
2978 #ifdef PRUNE_LIST_CPU_ONE
2979     int  ci_last = -1;
2980 #endif
2981
2982     d2l = nbl->work->d2;
2983
2984 #ifdef NBNXN_BBXXXX
2985     pbb_ci = nbl->work->pbb_ci;
2986 #else
2987     bb_ci  = nbl->work->bb_ci;
2988 #endif
2989     x_ci   = nbl->work->x_ci;
2990
2991     na_c = gridj->na_c;
2992
2993     for (cjo = 0; cjo < gridj->nsubc[scj]; cjo++)
2994     {
2995         cj4_ind   = (nbl->work->cj_ind >> NBNXN_GPU_JGROUP_SIZE_2LOG);
2996         cj_offset = nbl->work->cj_ind - cj4_ind*NBNXN_GPU_JGROUP_SIZE;
2997         cj4       = &nbl->cj4[cj4_ind];
2998
2999         cj = scj*GPU_NSUBCELL + cjo;
3000
3001         cj_gl = gridj->cell0*GPU_NSUBCELL + cj;
3002
3003         /* Initialize this j-subcell i-subcell list */
3004         cj4->cj[cj_offset] = cj_gl;
3005         imask              = 0;
3006
3007         if (sci_equals_scj)
3008         {
3009             ci1 = cjo + 1;
3010         }
3011         else
3012         {
3013             ci1 = gridi->nsubc[sci];
3014         }
3015
3016 #ifdef NBNXN_BBXXXX
3017         /* Determine all ci1 bb distances in one call with SIMD4 */
3018         subc_bb_dist2_simd4_xxxx(gridj->pbb+(cj>>STRIDE_PBB_2LOG)*NNBSBB_XXXX+(cj & (STRIDE_PBB-1)),
3019                                  ci1, pbb_ci, d2l);
3020         *ndistc += na_c*2;
3021 #endif
3022
3023         npair = 0;
3024         /* We use a fixed upper-bound instead of ci1 to help optimization */
3025         for (ci = 0; ci < GPU_NSUBCELL; ci++)
3026         {
3027             if (ci == ci1)
3028             {
3029                 break;
3030             }
3031
3032 #ifndef NBNXN_BBXXXX
3033             /* Determine the bb distance between ci and cj */
3034             d2l[ci]  = subc_bb_dist2(ci, bb_ci, cj, gridj->bb);
3035             *ndistc += 2;
3036 #endif
3037             d2 = d2l[ci];
3038
3039 #ifdef PRUNE_LIST_CPU_ALL
3040             /* Check if the distance is within the distance where
3041              * we use only the bounding box distance rbb,
3042              * or within the cut-off and there is at least one atom pair
3043              * within the cut-off. This check is very costly.
3044              */
3045             *ndistc += na_c*na_c;
3046             if (d2 < rbb2 ||
3047                 (d2 < rl2 &&
3048 #ifdef NBNXN_PBB_SIMD4
3049                  subc_in_range_simd4
3050 #else
3051                  subc_in_range_x
3052 #endif
3053                      (na_c, ci, x_ci, cj_gl, stride, x, rl2)))
3054 #else
3055             /* Check if the distance between the two bounding boxes
3056              * in within the pair-list cut-off.
3057              */
3058             if (d2 < rl2)
3059 #endif
3060             {
3061                 /* Flag this i-subcell to be taken into account */
3062                 imask |= (1U << (cj_offset*GPU_NSUBCELL+ci));
3063
3064 #ifdef PRUNE_LIST_CPU_ONE
3065                 ci_last = ci;
3066 #endif
3067
3068                 npair++;
3069             }
3070         }
3071
3072 #ifdef PRUNE_LIST_CPU_ONE
3073         /* If we only found 1 pair, check if any atoms are actually
3074          * within the cut-off, so we could get rid of it.
3075          */
3076         if (npair == 1 && d2l[ci_last] >= rbb2)
3077         {
3078             /* Avoid using function pointers here, as it's slower */
3079             if (
3080 #ifdef NBNXN_PBB_SIMD4
3081                 !subc_in_range_simd4
3082 #else
3083                 !subc_in_range_x
3084 #endif
3085                     (na_c, ci_last, x_ci, cj_gl, stride, x, rl2))
3086             {
3087                 imask &= ~(1U << (cj_offset*GPU_NSUBCELL+ci_last));
3088                 npair--;
3089             }
3090         }
3091 #endif
3092
3093         if (npair > 0)
3094         {
3095             /* We have a useful sj entry, close it now */
3096
3097             /* Set the exclucions for the ci== sj entry.
3098              * Here we don't bother to check if this entry is actually flagged,
3099              * as it will nearly always be in the list.
3100              */
3101             if (sci_equals_scj)
3102             {
3103                 set_self_and_newton_excls_supersub(nbl, cj4_ind, cj_offset, cjo);
3104             }
3105
3106             /* Copy the cluster interaction mask to the list */
3107             for (w = 0; w < NWARP; w++)
3108             {
3109                 cj4->imei[w].imask |= imask;
3110             }
3111
3112             nbl->work->cj_ind++;
3113
3114             /* Keep the count */
3115             nbl->nci_tot += npair;
3116
3117             /* Increase the closing index in i super-cell list */
3118             nbl->sci[nbl->nsci].cj4_ind_end =
3119                 ((nbl->work->cj_ind+NBNXN_GPU_JGROUP_SIZE-1) >> NBNXN_GPU_JGROUP_SIZE_2LOG);
3120         }
3121     }
3122 }
3123
3124 /* Set all atom-pair exclusions from the topology stored in excl
3125  * as masks in the pair-list for simple list i-entry nbl_ci
3126  */
3127 static void set_ci_top_excls(const nbnxn_search_t nbs,
3128                              nbnxn_pairlist_t    *nbl,
3129                              gmx_bool             diagRemoved,
3130                              int                  na_ci_2log,
3131                              int                  na_cj_2log,
3132                              const nbnxn_ci_t    *nbl_ci,
3133                              const t_blocka      *excl)
3134 {
3135     const int    *cell;
3136     int           ci;
3137     int           cj_ind_first, cj_ind_last;
3138     int           cj_first, cj_last;
3139     int           ndirect;
3140     int           i, ai, aj, si, eind, ge, se;
3141     int           found, cj_ind_0, cj_ind_1, cj_ind_m;
3142     int           cj_m;
3143     gmx_bool      Found_si;
3144     int           si_ind;
3145     nbnxn_excl_t *nbl_excl;
3146     int           inner_i, inner_e;
3147
3148     cell = nbs->cell;
3149
3150     if (nbl_ci->cj_ind_end == nbl_ci->cj_ind_start)
3151     {
3152         /* Empty list */
3153         return;
3154     }
3155
3156     ci = nbl_ci->ci;
3157
3158     cj_ind_first = nbl_ci->cj_ind_start;
3159     cj_ind_last  = nbl->ncj - 1;
3160
3161     cj_first = nbl->cj[cj_ind_first].cj;
3162     cj_last  = nbl->cj[cj_ind_last].cj;
3163
3164     /* Determine how many contiguous j-cells we have starting
3165      * from the first i-cell. This number can be used to directly
3166      * calculate j-cell indices for excluded atoms.
3167      */
3168     ndirect = 0;
3169     if (na_ci_2log == na_cj_2log)
3170     {
3171         while (cj_ind_first + ndirect <= cj_ind_last &&
3172                nbl->cj[cj_ind_first+ndirect].cj == ci + ndirect)
3173         {
3174             ndirect++;
3175         }
3176     }
3177 #ifdef NBNXN_SEARCH_BB_SIMD4
3178     else
3179     {
3180         while (cj_ind_first + ndirect <= cj_ind_last &&
3181                nbl->cj[cj_ind_first+ndirect].cj == ci_to_cj(na_cj_2log, ci) + ndirect)
3182         {
3183             ndirect++;
3184         }
3185     }
3186 #endif
3187
3188     /* Loop over the atoms in the i super-cell */
3189     for (i = 0; i < nbl->na_sc; i++)
3190     {
3191         ai = nbs->a[ci*nbl->na_sc+i];
3192         if (ai >= 0)
3193         {
3194             si  = (i>>na_ci_2log);
3195
3196             /* Loop over the topology-based exclusions for this i-atom */
3197             for (eind = excl->index[ai]; eind < excl->index[ai+1]; eind++)
3198             {
3199                 aj = excl->a[eind];
3200
3201                 if (aj == ai)
3202                 {
3203                     /* The self exclusion are already set, save some time */
3204                     continue;
3205                 }
3206
3207                 ge = cell[aj];
3208
3209                 /* Without shifts we only calculate interactions j>i
3210                  * for one-way pair-lists.
3211                  */
3212                 if (diagRemoved && ge <= ci*nbl->na_sc + i)
3213                 {
3214                     continue;
3215                 }
3216
3217                 se = (ge >> na_cj_2log);
3218
3219                 /* Could the cluster se be in our list? */
3220                 if (se >= cj_first && se <= cj_last)
3221                 {
3222                     if (se < cj_first + ndirect)
3223                     {
3224                         /* We can calculate cj_ind directly from se */
3225                         found = cj_ind_first + se - cj_first;
3226                     }
3227                     else
3228                     {
3229                         /* Search for se using bisection */
3230                         found    = -1;
3231                         cj_ind_0 = cj_ind_first + ndirect;
3232                         cj_ind_1 = cj_ind_last + 1;
3233                         while (found == -1 && cj_ind_0 < cj_ind_1)
3234                         {
3235                             cj_ind_m = (cj_ind_0 + cj_ind_1)>>1;
3236
3237                             cj_m = nbl->cj[cj_ind_m].cj;
3238
3239                             if (se == cj_m)
3240                             {
3241                                 found = cj_ind_m;
3242                             }
3243                             else if (se < cj_m)
3244                             {
3245                                 cj_ind_1 = cj_ind_m;
3246                             }
3247                             else
3248                             {
3249                                 cj_ind_0 = cj_ind_m + 1;
3250                             }
3251                         }
3252                     }
3253
3254                     if (found >= 0)
3255                     {
3256                         inner_i = i  - (si << na_ci_2log);
3257                         inner_e = ge - (se << na_cj_2log);
3258
3259                         nbl->cj[found].excl &= ~(1U<<((inner_i<<na_cj_2log) + inner_e));
3260 /* The next code line is usually not needed. We do not want to version
3261  * away the above line, because there is logic that relies on being
3262  * able to detect easily whether any exclusions exist. */
3263 #if (defined GMX_SIMD_IBM_QPX)
3264                         nbl->cj[found].interaction_mask_indices[inner_i] &= ~(1U << inner_e);
3265 #endif
3266                     }
3267                 }
3268             }
3269         }
3270     }
3271 }
3272
3273 /* Add a new i-entry to the FEP list and copy the i-properties */
3274 static gmx_inline void fep_list_new_nri_copy(t_nblist *nlist)
3275 {
3276     /* Add a new i-entry */
3277     nlist->nri++;
3278
3279     assert(nlist->nri < nlist->maxnri);
3280
3281     /* Duplicate the last i-entry, except for jindex, which continues */
3282     nlist->iinr[nlist->nri]   = nlist->iinr[nlist->nri-1];
3283     nlist->shift[nlist->nri]  = nlist->shift[nlist->nri-1];
3284     nlist->gid[nlist->nri]    = nlist->gid[nlist->nri-1];
3285     nlist->jindex[nlist->nri] = nlist->nrj;
3286 }
3287
3288 /* For load balancing of the free-energy lists over threads, we set
3289  * the maximum nrj size of an i-entry to 40. This leads to good
3290  * load balancing in the worst case scenario of a single perturbed
3291  * particle on 16 threads, while not introducing significant overhead.
3292  * Note that half of the perturbed pairs will anyhow end up in very small lists,
3293  * since non perturbed i-particles will see few perturbed j-particles).
3294  */
3295 const int max_nrj_fep = 40;
3296
3297 /* Exclude the perturbed pairs from the Verlet list. This is only done to avoid
3298  * singularities for overlapping particles (0/0), since the charges and
3299  * LJ parameters have been zeroed in the nbnxn data structure.
3300  * Simultaneously make a group pair list for the perturbed pairs.
3301  */
3302 static void make_fep_list(const nbnxn_search_t    nbs,
3303                           const nbnxn_atomdata_t *nbat,
3304                           nbnxn_pairlist_t       *nbl,
3305                           gmx_bool                bDiagRemoved,
3306                           nbnxn_ci_t             *nbl_ci,
3307                           const nbnxn_grid_t     *gridi,
3308                           const nbnxn_grid_t     *gridj,
3309                           t_nblist               *nlist)
3310 {
3311     int      ci, cj_ind_start, cj_ind_end, cj_ind, cja, cjr;
3312     int      nri_max;
3313     int      ngid, gid_i = 0, gid_j, gid;
3314     int      egp_shift, egp_mask;
3315     int      gid_cj = 0;
3316     int      i, j, ind_i, ind_j, ai, aj;
3317     int      nri;
3318     gmx_bool bFEP_i, bFEP_i_all;
3319
3320     if (nbl_ci->cj_ind_end == nbl_ci->cj_ind_start)
3321     {
3322         /* Empty list */
3323         return;
3324     }
3325
3326     ci = nbl_ci->ci;
3327
3328     cj_ind_start = nbl_ci->cj_ind_start;
3329     cj_ind_end   = nbl_ci->cj_ind_end;
3330
3331     /* In worst case we have alternating energy groups
3332      * and create #atom-pair lists, which means we need the size
3333      * of a cluster pair (na_ci*na_cj) times the number of cj's.
3334      */
3335     nri_max = nbl->na_ci*nbl->na_cj*(cj_ind_end - cj_ind_start);
3336     if (nlist->nri + nri_max > nlist->maxnri)
3337     {
3338         nlist->maxnri = over_alloc_large(nlist->nri + nri_max);
3339         reallocate_nblist(nlist);
3340     }
3341
3342     ngid = nbat->nenergrp;
3343
3344     if (ngid*gridj->na_cj > sizeof(gid_cj)*8)
3345     {
3346         gmx_fatal(FARGS, "The Verlet scheme with %dx%d kernels and free-energy only supports up to %d energy groups",
3347                   gridi->na_c, gridj->na_cj, (sizeof(gid_cj)*8)/gridj->na_cj);
3348     }
3349
3350     egp_shift = nbat->neg_2log;
3351     egp_mask  = (1<<nbat->neg_2log) - 1;
3352
3353     /* Loop over the atoms in the i sub-cell */
3354     bFEP_i_all = TRUE;
3355     for (i = 0; i < nbl->na_ci; i++)
3356     {
3357         ind_i = ci*nbl->na_ci + i;
3358         ai    = nbs->a[ind_i];
3359         if (ai >= 0)
3360         {
3361             nri                  = nlist->nri;
3362             nlist->jindex[nri+1] = nlist->jindex[nri];
3363             nlist->iinr[nri]     = ai;
3364             /* The actual energy group pair index is set later */
3365             nlist->gid[nri]      = 0;
3366             nlist->shift[nri]    = nbl_ci->shift & NBNXN_CI_SHIFT;
3367
3368             bFEP_i = gridi->fep[ci - gridi->cell0] & (1 << i);
3369
3370             bFEP_i_all = bFEP_i_all && bFEP_i;
3371
3372             if ((nlist->nrj + cj_ind_end - cj_ind_start)*nbl->na_cj > nlist->maxnrj)
3373             {
3374                 nlist->maxnrj = over_alloc_small((nlist->nrj + cj_ind_end - cj_ind_start)*nbl->na_cj);
3375                 srenew(nlist->jjnr,     nlist->maxnrj);
3376                 srenew(nlist->excl_fep, nlist->maxnrj);
3377             }
3378
3379             if (ngid > 1)
3380             {
3381                 gid_i = (nbat->energrp[ci] >> (egp_shift*i)) & egp_mask;
3382             }
3383
3384             for (cj_ind = cj_ind_start; cj_ind < cj_ind_end; cj_ind++)
3385             {
3386                 unsigned int fep_cj;
3387
3388                 cja = nbl->cj[cj_ind].cj;
3389
3390                 if (gridj->na_cj == gridj->na_c)
3391                 {
3392                     cjr    = cja - gridj->cell0;
3393                     fep_cj = gridj->fep[cjr];
3394                     if (ngid > 1)
3395                     {
3396                         gid_cj = nbat->energrp[cja];
3397                     }
3398                 }
3399                 else if (2*gridj->na_cj == gridj->na_c)
3400                 {
3401                     cjr    = cja - gridj->cell0*2;
3402                     /* Extract half of the ci fep/energrp mask */
3403                     fep_cj = (gridj->fep[cjr>>1] >> ((cjr&1)*gridj->na_cj)) & ((1<<gridj->na_cj) - 1);
3404                     if (ngid > 1)
3405                     {
3406                         gid_cj = nbat->energrp[cja>>1] >> ((cja&1)*gridj->na_cj*egp_shift) & ((1<<(gridj->na_cj*egp_shift)) - 1);
3407                     }
3408                 }
3409                 else
3410                 {
3411                     cjr    = cja - (gridj->cell0>>1);
3412                     /* Combine two ci fep masks/energrp */
3413                     fep_cj = gridj->fep[cjr*2] + (gridj->fep[cjr*2+1] << gridj->na_c);
3414                     if (ngid > 1)
3415                     {
3416                         gid_cj = nbat->energrp[cja*2] + (nbat->energrp[cja*2+1] << (gridj->na_c*egp_shift));
3417                     }
3418                 }
3419
3420                 if (bFEP_i || fep_cj != 0)
3421                 {
3422                     for (j = 0; j < nbl->na_cj; j++)
3423                     {
3424                         /* Is this interaction perturbed and not excluded? */
3425                         ind_j = cja*nbl->na_cj + j;
3426                         aj    = nbs->a[ind_j];
3427                         if (aj >= 0 &&
3428                             (bFEP_i || (fep_cj & (1 << j))) &&
3429                             (!bDiagRemoved || ind_j >= ind_i))
3430                         {
3431                             if (ngid > 1)
3432                             {
3433                                 gid_j = (gid_cj >> (j*egp_shift)) & egp_mask;
3434                                 gid   = GID(gid_i, gid_j, ngid);
3435
3436                                 if (nlist->nrj > nlist->jindex[nri] &&
3437                                     nlist->gid[nri] != gid)
3438                                 {
3439                                     /* Energy group pair changed: new list */
3440                                     fep_list_new_nri_copy(nlist);
3441                                     nri = nlist->nri;
3442                                 }
3443                                 nlist->gid[nri] = gid;
3444                             }
3445
3446                             if (nlist->nrj - nlist->jindex[nri] >= max_nrj_fep)
3447                             {
3448                                 fep_list_new_nri_copy(nlist);
3449                                 nri = nlist->nri;
3450                             }
3451
3452                             /* Add it to the FEP list */
3453                             nlist->jjnr[nlist->nrj]     = aj;
3454                             nlist->excl_fep[nlist->nrj] = (nbl->cj[cj_ind].excl >> (i*nbl->na_cj + j)) & 1;
3455                             nlist->nrj++;
3456
3457                             /* Exclude it from the normal list.
3458                              * Note that the charge has been set to zero,
3459                              * but we need to avoid 0/0, as perturbed atoms
3460                              * can be on top of each other.
3461                              */
3462                             nbl->cj[cj_ind].excl &= ~(1U << (i*nbl->na_cj + j));
3463                         }
3464                     }
3465                 }
3466             }
3467
3468             if (nlist->nrj > nlist->jindex[nri])
3469             {
3470                 /* Actually add this new, non-empty, list */
3471                 nlist->nri++;
3472                 nlist->jindex[nlist->nri] = nlist->nrj;
3473             }
3474         }
3475     }
3476
3477     if (bFEP_i_all)
3478     {
3479         /* All interactions are perturbed, we can skip this entry */
3480         nbl_ci->cj_ind_end = cj_ind_start;
3481     }
3482 }
3483
3484 /* Return the index of atom a within a cluster */
3485 static gmx_inline int cj_mod_cj4(int cj)
3486 {
3487     return cj & (NBNXN_GPU_JGROUP_SIZE - 1);
3488 }
3489
3490 /* Convert a j-cluster to a cj4 group */
3491 static gmx_inline int cj_to_cj4(int cj)
3492 {
3493     return cj >> NBNXN_GPU_JGROUP_SIZE_2LOG;
3494 }
3495
3496 /* Return the index of an j-atom within a warp */
3497 static gmx_inline int a_mod_wj(int a)
3498 {
3499     return a & (NBNXN_GPU_CLUSTER_SIZE/2 - 1);
3500 }
3501
3502 /* As make_fep_list above, but for super/sub lists. */
3503 static void make_fep_list_supersub(const nbnxn_search_t    nbs,
3504                                    const nbnxn_atomdata_t *nbat,
3505                                    nbnxn_pairlist_t       *nbl,
3506                                    gmx_bool                bDiagRemoved,
3507                                    const nbnxn_sci_t      *nbl_sci,
3508                                    real                    shx,
3509                                    real                    shy,
3510                                    real                    shz,
3511                                    real                    rlist_fep2,
3512                                    const nbnxn_grid_t     *gridi,
3513                                    const nbnxn_grid_t     *gridj,
3514                                    t_nblist               *nlist)
3515 {
3516     int                sci, cj4_ind_start, cj4_ind_end, cj4_ind, gcj, cjr;
3517     int                nri_max;
3518     int                c, c_abs;
3519     int                i, j, ind_i, ind_j, ai, aj;
3520     int                nri;
3521     gmx_bool           bFEP_i;
3522     real               xi, yi, zi;
3523     const nbnxn_cj4_t *cj4;
3524
3525     if (nbl_sci->cj4_ind_end == nbl_sci->cj4_ind_start)
3526     {
3527         /* Empty list */
3528         return;
3529     }
3530
3531     sci = nbl_sci->sci;
3532
3533     cj4_ind_start = nbl_sci->cj4_ind_start;
3534     cj4_ind_end   = nbl_sci->cj4_ind_end;
3535
3536     /* Here we process one super-cell, max #atoms na_sc, versus a list
3537      * cj4 entries, each with max NBNXN_GPU_JGROUP_SIZE cj's, each
3538      * of size na_cj atoms.
3539      * On the GPU we don't support energy groups (yet).
3540      * So for each of the na_sc i-atoms, we need max one FEP list
3541      * for each max_nrj_fep j-atoms.
3542      */
3543     nri_max = nbl->na_sc*nbl->na_cj*(1 + ((cj4_ind_end - cj4_ind_start)*NBNXN_GPU_JGROUP_SIZE)/max_nrj_fep);
3544     if (nlist->nri + nri_max > nlist->maxnri)
3545     {
3546         nlist->maxnri = over_alloc_large(nlist->nri + nri_max);
3547         reallocate_nblist(nlist);
3548     }
3549
3550     /* Loop over the atoms in the i super-cluster */
3551     for (c = 0; c < GPU_NSUBCELL; c++)
3552     {
3553         c_abs = sci*GPU_NSUBCELL + c;
3554
3555         for (i = 0; i < nbl->na_ci; i++)
3556         {
3557             ind_i = c_abs*nbl->na_ci + i;
3558             ai    = nbs->a[ind_i];
3559             if (ai >= 0)
3560             {
3561                 nri                  = nlist->nri;
3562                 nlist->jindex[nri+1] = nlist->jindex[nri];
3563                 nlist->iinr[nri]     = ai;
3564                 /* With GPUs, energy groups are not supported */
3565                 nlist->gid[nri]      = 0;
3566                 nlist->shift[nri]    = nbl_sci->shift & NBNXN_CI_SHIFT;
3567
3568                 bFEP_i = (gridi->fep[c_abs - gridi->cell0] & (1 << i));
3569
3570                 xi = nbat->x[ind_i*nbat->xstride+XX] + shx;
3571                 yi = nbat->x[ind_i*nbat->xstride+YY] + shy;
3572                 zi = nbat->x[ind_i*nbat->xstride+ZZ] + shz;
3573
3574                 if ((nlist->nrj + cj4_ind_end - cj4_ind_start)*NBNXN_GPU_JGROUP_SIZE*nbl->na_cj > nlist->maxnrj)
3575                 {
3576                     nlist->maxnrj = over_alloc_small((nlist->nrj + cj4_ind_end - cj4_ind_start)*NBNXN_GPU_JGROUP_SIZE*nbl->na_cj);
3577                     srenew(nlist->jjnr,     nlist->maxnrj);
3578                     srenew(nlist->excl_fep, nlist->maxnrj);
3579                 }
3580
3581                 for (cj4_ind = cj4_ind_start; cj4_ind < cj4_ind_end; cj4_ind++)
3582                 {
3583                     cj4 = &nbl->cj4[cj4_ind];
3584
3585                     for (gcj = 0; gcj < NBNXN_GPU_JGROUP_SIZE; gcj++)
3586                     {
3587                         unsigned int fep_cj;
3588
3589                         if ((cj4->imei[0].imask & (1U << (gcj*GPU_NSUBCELL + c))) == 0)
3590                         {
3591                             /* Skip this ci for this cj */
3592                             continue;
3593                         }
3594
3595                         cjr = cj4->cj[gcj] - gridj->cell0*GPU_NSUBCELL;
3596
3597                         fep_cj = gridj->fep[cjr];
3598
3599                         if (bFEP_i || fep_cj != 0)
3600                         {
3601                             for (j = 0; j < nbl->na_cj; j++)
3602                             {
3603                                 /* Is this interaction perturbed and not excluded? */
3604                                 ind_j = (gridj->cell0*GPU_NSUBCELL + cjr)*nbl->na_cj + j;
3605                                 aj    = nbs->a[ind_j];
3606                                 if (aj >= 0 &&
3607                                     (bFEP_i || (fep_cj & (1 << j))) &&
3608                                     (!bDiagRemoved || ind_j >= ind_i))
3609                                 {
3610                                     nbnxn_excl_t *excl;
3611                                     int           excl_pair;
3612                                     unsigned int  excl_bit;
3613                                     real          dx, dy, dz;
3614
3615                                     get_nbl_exclusions_1(nbl, cj4_ind, j>>2, &excl);
3616
3617                                     excl_pair = a_mod_wj(j)*nbl->na_ci + i;
3618                                     excl_bit  = (1U << (gcj*GPU_NSUBCELL + c));
3619
3620                                     dx = nbat->x[ind_j*nbat->xstride+XX] - xi;
3621                                     dy = nbat->x[ind_j*nbat->xstride+YY] - yi;
3622                                     dz = nbat->x[ind_j*nbat->xstride+ZZ] - zi;
3623
3624                                     /* The unpruned GPU list has more than 2/3
3625                                      * of the atom pairs beyond rlist. Using
3626                                      * this list will cause a lot of overhead
3627                                      * in the CPU FEP kernels, especially
3628                                      * relative to the fast GPU kernels.
3629                                      * So we prune the FEP list here.
3630                                      */
3631                                     if (dx*dx + dy*dy + dz*dz < rlist_fep2)
3632                                     {
3633                                         if (nlist->nrj - nlist->jindex[nri] >= max_nrj_fep)
3634                                         {
3635                                             fep_list_new_nri_copy(nlist);
3636                                             nri = nlist->nri;
3637                                         }
3638
3639                                         /* Add it to the FEP list */
3640                                         nlist->jjnr[nlist->nrj]     = aj;
3641                                         nlist->excl_fep[nlist->nrj] = (excl->pair[excl_pair] & excl_bit) ? 1 : 0;
3642                                         nlist->nrj++;
3643                                     }
3644
3645                                     /* Exclude it from the normal list.
3646                                      * Note that the charge and LJ parameters have
3647                                      * been set to zero, but we need to avoid 0/0,
3648                                      * as perturbed atoms can be on top of each other.
3649                                      */
3650                                     excl->pair[excl_pair] &= ~excl_bit;
3651                                 }
3652                             }
3653
3654                             /* Note that we could mask out this pair in imask
3655                              * if all i- and/or all j-particles are perturbed.
3656                              * But since the perturbed pairs on the CPU will
3657                              * take an order of magnitude more time, the GPU
3658                              * will finish before the CPU and there is no gain.
3659                              */
3660                         }
3661                     }
3662                 }
3663
3664                 if (nlist->nrj > nlist->jindex[nri])
3665                 {
3666                     /* Actually add this new, non-empty, list */
3667                     nlist->nri++;
3668                     nlist->jindex[nlist->nri] = nlist->nrj;
3669                 }
3670             }
3671         }
3672     }
3673 }
3674
3675 /* Set all atom-pair exclusions from the topology stored in excl
3676  * as masks in the pair-list for i-super-cell entry nbl_sci
3677  */
3678 static void set_sci_top_excls(const nbnxn_search_t nbs,
3679                               nbnxn_pairlist_t    *nbl,
3680                               gmx_bool             diagRemoved,
3681                               int                  na_c_2log,
3682                               const nbnxn_sci_t   *nbl_sci,
3683                               const t_blocka      *excl)
3684 {
3685     const int    *cell;
3686     int           na_c;
3687     int           sci;
3688     int           cj_ind_first, cj_ind_last;
3689     int           cj_first, cj_last;
3690     int           ndirect;
3691     int           i, ai, aj, si, eind, ge, se;
3692     int           found, cj_ind_0, cj_ind_1, cj_ind_m;
3693     int           cj_m;
3694     gmx_bool      Found_si;
3695     int           si_ind;
3696     nbnxn_excl_t *nbl_excl;
3697     int           inner_i, inner_e, w;
3698
3699     cell = nbs->cell;
3700
3701     na_c = nbl->na_ci;
3702
3703     if (nbl_sci->cj4_ind_end == nbl_sci->cj4_ind_start)
3704     {
3705         /* Empty list */
3706         return;
3707     }
3708
3709     sci = nbl_sci->sci;
3710
3711     cj_ind_first = nbl_sci->cj4_ind_start*NBNXN_GPU_JGROUP_SIZE;
3712     cj_ind_last  = nbl->work->cj_ind - 1;
3713
3714     cj_first = nbl->cj4[nbl_sci->cj4_ind_start].cj[0];
3715     cj_last  = nbl_cj(nbl, cj_ind_last);
3716
3717     /* Determine how many contiguous j-clusters we have starting
3718      * from the first i-cluster. This number can be used to directly
3719      * calculate j-cluster indices for excluded atoms.
3720      */
3721     ndirect = 0;
3722     while (cj_ind_first + ndirect <= cj_ind_last &&
3723            nbl_cj(nbl, cj_ind_first+ndirect) == sci*GPU_NSUBCELL + ndirect)
3724     {
3725         ndirect++;
3726     }
3727
3728     /* Loop over the atoms in the i super-cell */
3729     for (i = 0; i < nbl->na_sc; i++)
3730     {
3731         ai = nbs->a[sci*nbl->na_sc+i];
3732         if (ai >= 0)
3733         {
3734             si  = (i>>na_c_2log);
3735
3736             /* Loop over the topology-based exclusions for this i-atom */
3737             for (eind = excl->index[ai]; eind < excl->index[ai+1]; eind++)
3738             {
3739                 aj = excl->a[eind];
3740
3741                 if (aj == ai)
3742                 {
3743                     /* The self exclusion are already set, save some time */
3744                     continue;
3745                 }
3746
3747                 ge = cell[aj];
3748
3749                 /* Without shifts we only calculate interactions j>i
3750                  * for one-way pair-lists.
3751                  */
3752                 if (diagRemoved && ge <= sci*nbl->na_sc + i)
3753                 {
3754                     continue;
3755                 }
3756
3757                 se = ge>>na_c_2log;
3758                 /* Could the cluster se be in our list? */
3759                 if (se >= cj_first && se <= cj_last)
3760                 {
3761                     if (se < cj_first + ndirect)
3762                     {
3763                         /* We can calculate cj_ind directly from se */
3764                         found = cj_ind_first + se - cj_first;
3765                     }
3766                     else
3767                     {
3768                         /* Search for se using bisection */
3769                         found    = -1;
3770                         cj_ind_0 = cj_ind_first + ndirect;
3771                         cj_ind_1 = cj_ind_last + 1;
3772                         while (found == -1 && cj_ind_0 < cj_ind_1)
3773                         {
3774                             cj_ind_m = (cj_ind_0 + cj_ind_1)>>1;
3775
3776                             cj_m = nbl_cj(nbl, cj_ind_m);
3777
3778                             if (se == cj_m)
3779                             {
3780                                 found = cj_ind_m;
3781                             }
3782                             else if (se < cj_m)
3783                             {
3784                                 cj_ind_1 = cj_ind_m;
3785                             }
3786                             else
3787                             {
3788                                 cj_ind_0 = cj_ind_m + 1;
3789                             }
3790                         }
3791                     }
3792
3793                     if (found >= 0)
3794                     {
3795                         inner_i = i  - si*na_c;
3796                         inner_e = ge - se*na_c;
3797
3798                         if (nbl_imask0(nbl, found) & (1U << (cj_mod_cj4(found)*GPU_NSUBCELL + si)))
3799                         {
3800                             w       = (inner_e >> 2);
3801
3802                             get_nbl_exclusions_1(nbl, cj_to_cj4(found), w, &nbl_excl);
3803
3804                             nbl_excl->pair[a_mod_wj(inner_e)*nbl->na_ci+inner_i] &=
3805                                 ~(1U << (cj_mod_cj4(found)*GPU_NSUBCELL + si));
3806                         }
3807                     }
3808                 }
3809             }
3810         }
3811     }
3812 }
3813
3814 /* Reallocate the simple ci list for at least n entries */
3815 static void nb_realloc_ci(nbnxn_pairlist_t *nbl, int n)
3816 {
3817     nbl->ci_nalloc = over_alloc_small(n);
3818     nbnxn_realloc_void((void **)&nbl->ci,
3819                        nbl->nci*sizeof(*nbl->ci),
3820                        nbl->ci_nalloc*sizeof(*nbl->ci),
3821                        nbl->alloc, nbl->free);
3822 }
3823
3824 /* Reallocate the super-cell sci list for at least n entries */
3825 static void nb_realloc_sci(nbnxn_pairlist_t *nbl, int n)
3826 {
3827     nbl->sci_nalloc = over_alloc_small(n);
3828     nbnxn_realloc_void((void **)&nbl->sci,
3829                        nbl->nsci*sizeof(*nbl->sci),
3830                        nbl->sci_nalloc*sizeof(*nbl->sci),
3831                        nbl->alloc, nbl->free);
3832 }
3833
3834 /* Make a new ci entry at index nbl->nci */
3835 static void new_ci_entry(nbnxn_pairlist_t *nbl, int ci, int shift, int flags)
3836 {
3837     if (nbl->nci + 1 > nbl->ci_nalloc)
3838     {
3839         nb_realloc_ci(nbl, nbl->nci+1);
3840     }
3841     nbl->ci[nbl->nci].ci            = ci;
3842     nbl->ci[nbl->nci].shift         = shift;
3843     /* Store the interaction flags along with the shift */
3844     nbl->ci[nbl->nci].shift        |= flags;
3845     nbl->ci[nbl->nci].cj_ind_start  = nbl->ncj;
3846     nbl->ci[nbl->nci].cj_ind_end    = nbl->ncj;
3847 }
3848
3849 /* Make a new sci entry at index nbl->nsci */
3850 static void new_sci_entry(nbnxn_pairlist_t *nbl, int sci, int shift)
3851 {
3852     if (nbl->nsci + 1 > nbl->sci_nalloc)
3853     {
3854         nb_realloc_sci(nbl, nbl->nsci+1);
3855     }
3856     nbl->sci[nbl->nsci].sci           = sci;
3857     nbl->sci[nbl->nsci].shift         = shift;
3858     nbl->sci[nbl->nsci].cj4_ind_start = nbl->ncj4;
3859     nbl->sci[nbl->nsci].cj4_ind_end   = nbl->ncj4;
3860 }
3861
3862 /* Sort the simple j-list cj on exclusions.
3863  * Entries with exclusions will all be sorted to the beginning of the list.
3864  */
3865 static void sort_cj_excl(nbnxn_cj_t *cj, int ncj,
3866                          nbnxn_list_work_t *work)
3867 {
3868     int jnew, j;
3869
3870     if (ncj > work->cj_nalloc)
3871     {
3872         work->cj_nalloc = over_alloc_large(ncj);
3873         srenew(work->cj, work->cj_nalloc);
3874     }
3875
3876     /* Make a list of the j-cells involving exclusions */
3877     jnew = 0;
3878     for (j = 0; j < ncj; j++)
3879     {
3880         if (cj[j].excl != NBNXN_INTERACTION_MASK_ALL)
3881         {
3882             work->cj[jnew++] = cj[j];
3883         }
3884     }
3885     /* Check if there are exclusions at all or not just the first entry */
3886     if (!((jnew == 0) ||
3887           (jnew == 1 && cj[0].excl != NBNXN_INTERACTION_MASK_ALL)))
3888     {
3889         for (j = 0; j < ncj; j++)
3890         {
3891             if (cj[j].excl == NBNXN_INTERACTION_MASK_ALL)
3892             {
3893                 work->cj[jnew++] = cj[j];
3894             }
3895         }
3896         for (j = 0; j < ncj; j++)
3897         {
3898             cj[j] = work->cj[j];
3899         }
3900     }
3901 }
3902
3903 /* Close this simple list i entry */
3904 static void close_ci_entry_simple(nbnxn_pairlist_t *nbl)
3905 {
3906     int jlen;
3907
3908     /* All content of the new ci entry have already been filled correctly,
3909      * we only need to increase the count here (for non empty lists).
3910      */
3911     jlen = nbl->ci[nbl->nci].cj_ind_end - nbl->ci[nbl->nci].cj_ind_start;
3912     if (jlen > 0)
3913     {
3914         sort_cj_excl(nbl->cj+nbl->ci[nbl->nci].cj_ind_start, jlen, nbl->work);
3915
3916         /* The counts below are used for non-bonded pair/flop counts
3917          * and should therefore match the available kernel setups.
3918          */
3919         if (!(nbl->ci[nbl->nci].shift & NBNXN_CI_DO_COUL(0)))
3920         {
3921             nbl->work->ncj_noq += jlen;
3922         }
3923         else if ((nbl->ci[nbl->nci].shift & NBNXN_CI_HALF_LJ(0)) ||
3924                  !(nbl->ci[nbl->nci].shift & NBNXN_CI_DO_LJ(0)))
3925         {
3926             nbl->work->ncj_hlj += jlen;
3927         }
3928
3929         nbl->nci++;
3930     }
3931 }
3932
3933 /* Split sci entry for load balancing on the GPU.
3934  * Splitting ensures we have enough lists to fully utilize the whole GPU.
3935  * With progBal we generate progressively smaller lists, which improves
3936  * load balancing. As we only know the current count on our own thread,
3937  * we will need to estimate the current total amount of i-entries.
3938  * As the lists get concatenated later, this estimate depends
3939  * both on nthread and our own thread index.
3940  */
3941 static void split_sci_entry(nbnxn_pairlist_t *nbl,
3942                             int nsp_max_av, gmx_bool progBal, int nc_bal,
3943                             int thread, int nthread)
3944 {
3945     int nsci_est;
3946     int nsp_max;
3947     int cj4_start, cj4_end, j4len, cj4;
3948     int sci;
3949     int nsp, nsp_sci, nsp_cj4, nsp_cj4_e, nsp_cj4_p;
3950     int p;
3951
3952     if (progBal)
3953     {
3954         /* Estimate the total numbers of ci's of the nblist combined
3955          * over all threads using the target number of ci's.
3956          */
3957         nsci_est = nc_bal*thread/nthread + nbl->nsci;
3958
3959         /* The first ci blocks should be larger, to avoid overhead.
3960          * The last ci blocks should be smaller, to improve load balancing.
3961          */
3962         nsp_max = max(1,
3963                       nsp_max_av*nc_bal*3/(2*(nsci_est - 1 + nc_bal)));
3964     }
3965     else
3966     {
3967         nsp_max = nsp_max_av;
3968     }
3969
3970     cj4_start = nbl->sci[nbl->nsci-1].cj4_ind_start;
3971     cj4_end   = nbl->sci[nbl->nsci-1].cj4_ind_end;
3972     j4len     = cj4_end - cj4_start;
3973
3974     if (j4len > 1 && j4len*GPU_NSUBCELL*NBNXN_GPU_JGROUP_SIZE > nsp_max)
3975     {
3976         /* Remove the last ci entry and process the cj4's again */
3977         nbl->nsci -= 1;
3978
3979         sci        = nbl->nsci;
3980         nsp        = 0;
3981         nsp_sci    = 0;
3982         nsp_cj4_e  = 0;
3983         nsp_cj4    = 0;
3984         for (cj4 = cj4_start; cj4 < cj4_end; cj4++)
3985         {
3986             nsp_cj4_p = nsp_cj4;
3987             /* Count the number of cluster pairs in this cj4 group */
3988             nsp_cj4   = 0;
3989             for (p = 0; p < GPU_NSUBCELL*NBNXN_GPU_JGROUP_SIZE; p++)
3990             {
3991                 nsp_cj4 += (nbl->cj4[cj4].imei[0].imask >> p) & 1;
3992             }
3993
3994             if (nsp_cj4 > 0 && nsp + nsp_cj4 > nsp_max)
3995             {
3996                 /* Split the list at cj4 */
3997                 nbl->sci[sci].cj4_ind_end = cj4;
3998                 /* Create a new sci entry */
3999                 sci++;
4000                 nbl->nsci++;
4001                 if (nbl->nsci+1 > nbl->sci_nalloc)
4002                 {
4003                     nb_realloc_sci(nbl, nbl->nsci+1);
4004                 }
4005                 nbl->sci[sci].sci           = nbl->sci[nbl->nsci-1].sci;
4006                 nbl->sci[sci].shift         = nbl->sci[nbl->nsci-1].shift;
4007                 nbl->sci[sci].cj4_ind_start = cj4;
4008                 nsp_sci                     = nsp;
4009                 nsp_cj4_e                   = nsp_cj4_p;
4010                 nsp                         = 0;
4011             }
4012             nsp += nsp_cj4;
4013         }
4014
4015         /* Put the remaining cj4's in the last sci entry */
4016         nbl->sci[sci].cj4_ind_end = cj4_end;
4017
4018         /* Possibly balance out the last two sci's
4019          * by moving the last cj4 of the second last sci.
4020          */
4021         if (nsp_sci - nsp_cj4_e >= nsp + nsp_cj4_e)
4022         {
4023             nbl->sci[sci-1].cj4_ind_end--;
4024             nbl->sci[sci].cj4_ind_start--;
4025         }
4026
4027         nbl->nsci++;
4028     }
4029 }
4030
4031 /* Clost this super/sub list i entry */
4032 static void close_ci_entry_supersub(nbnxn_pairlist_t *nbl,
4033                                     int nsp_max_av,
4034                                     gmx_bool progBal, int nc_bal,
4035                                     int thread, int nthread)
4036 {
4037     int j4len, tlen;
4038     int nb, b;
4039
4040     /* All content of the new ci entry have already been filled correctly,
4041      * we only need to increase the count here (for non empty lists).
4042      */
4043     j4len = nbl->sci[nbl->nsci].cj4_ind_end - nbl->sci[nbl->nsci].cj4_ind_start;
4044     if (j4len > 0)
4045     {
4046         /* We can only have complete blocks of 4 j-entries in a list,
4047          * so round the count up before closing.
4048          */
4049         nbl->ncj4         = ((nbl->work->cj_ind + NBNXN_GPU_JGROUP_SIZE - 1) >> NBNXN_GPU_JGROUP_SIZE_2LOG);
4050         nbl->work->cj_ind = nbl->ncj4*NBNXN_GPU_JGROUP_SIZE;
4051
4052         nbl->nsci++;
4053
4054         if (nsp_max_av > 0)
4055         {
4056             /* Measure the size of the new entry and potentially split it */
4057             split_sci_entry(nbl, nsp_max_av, progBal, nc_bal, thread, nthread);
4058         }
4059     }
4060 }
4061
4062 /* Syncs the working array before adding another grid pair to the list */
4063 static void sync_work(nbnxn_pairlist_t *nbl)
4064 {
4065     if (!nbl->bSimple)
4066     {
4067         nbl->work->cj_ind   = nbl->ncj4*NBNXN_GPU_JGROUP_SIZE;
4068         nbl->work->cj4_init = nbl->ncj4;
4069     }
4070 }
4071
4072 /* Clears an nbnxn_pairlist_t data structure */
4073 static void clear_pairlist(nbnxn_pairlist_t *nbl)
4074 {
4075     nbl->nci           = 0;
4076     nbl->nsci          = 0;
4077     nbl->ncj           = 0;
4078     nbl->ncj4          = 0;
4079     nbl->nci_tot       = 0;
4080     nbl->nexcl         = 1;
4081
4082     nbl->work->ncj_noq = 0;
4083     nbl->work->ncj_hlj = 0;
4084 }
4085
4086 /* Clears a group scheme pair list */
4087 static void clear_pairlist_fep(t_nblist *nl)
4088 {
4089     nl->nri = 0;
4090     nl->nrj = 0;
4091     if (nl->jindex == NULL)
4092     {
4093         snew(nl->jindex, 1);
4094     }
4095     nl->jindex[0] = 0;
4096 }
4097
4098 /* Sets a simple list i-cell bounding box, including PBC shift */
4099 static gmx_inline void set_icell_bb_simple(const nbnxn_bb_t *bb, int ci,
4100                                            real shx, real shy, real shz,
4101                                            nbnxn_bb_t *bb_ci)
4102 {
4103     bb_ci->lower[BB_X] = bb[ci].lower[BB_X] + shx;
4104     bb_ci->lower[BB_Y] = bb[ci].lower[BB_Y] + shy;
4105     bb_ci->lower[BB_Z] = bb[ci].lower[BB_Z] + shz;
4106     bb_ci->upper[BB_X] = bb[ci].upper[BB_X] + shx;
4107     bb_ci->upper[BB_Y] = bb[ci].upper[BB_Y] + shy;
4108     bb_ci->upper[BB_Z] = bb[ci].upper[BB_Z] + shz;
4109 }
4110
4111 #ifdef NBNXN_BBXXXX
4112 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
4113 static void set_icell_bbxxxx_supersub(const float *bb, int ci,
4114                                       real shx, real shy, real shz,
4115                                       float *bb_ci)
4116 {
4117     int ia, m, i;
4118
4119     ia = ci*(GPU_NSUBCELL>>STRIDE_PBB_2LOG)*NNBSBB_XXXX;
4120     for (m = 0; m < (GPU_NSUBCELL>>STRIDE_PBB_2LOG)*NNBSBB_XXXX; m += NNBSBB_XXXX)
4121     {
4122         for (i = 0; i < STRIDE_PBB; i++)
4123         {
4124             bb_ci[m+0*STRIDE_PBB+i] = bb[ia+m+0*STRIDE_PBB+i] + shx;
4125             bb_ci[m+1*STRIDE_PBB+i] = bb[ia+m+1*STRIDE_PBB+i] + shy;
4126             bb_ci[m+2*STRIDE_PBB+i] = bb[ia+m+2*STRIDE_PBB+i] + shz;
4127             bb_ci[m+3*STRIDE_PBB+i] = bb[ia+m+3*STRIDE_PBB+i] + shx;
4128             bb_ci[m+4*STRIDE_PBB+i] = bb[ia+m+4*STRIDE_PBB+i] + shy;
4129             bb_ci[m+5*STRIDE_PBB+i] = bb[ia+m+5*STRIDE_PBB+i] + shz;
4130         }
4131     }
4132 }
4133 #endif
4134
4135 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
4136 static void set_icell_bb_supersub(const nbnxn_bb_t *bb, int ci,
4137                                   real shx, real shy, real shz,
4138                                   nbnxn_bb_t *bb_ci)
4139 {
4140     int i;
4141
4142     for (i = 0; i < GPU_NSUBCELL; i++)
4143     {
4144         set_icell_bb_simple(bb, ci*GPU_NSUBCELL+i,
4145                             shx, shy, shz,
4146                             &bb_ci[i]);
4147     }
4148 }
4149
4150 /* Copies PBC shifted i-cell atom coordinates x,y,z to working array */
4151 static void icell_set_x_simple(int ci,
4152                                real shx, real shy, real shz,
4153                                int gmx_unused na_c,
4154                                int stride, const real *x,
4155                                nbnxn_list_work_t *work)
4156 {
4157     int  ia, i;
4158
4159     ia = ci*NBNXN_CPU_CLUSTER_I_SIZE;
4160
4161     for (i = 0; i < NBNXN_CPU_CLUSTER_I_SIZE; i++)
4162     {
4163         work->x_ci[i*STRIDE_XYZ+XX] = x[(ia+i)*stride+XX] + shx;
4164         work->x_ci[i*STRIDE_XYZ+YY] = x[(ia+i)*stride+YY] + shy;
4165         work->x_ci[i*STRIDE_XYZ+ZZ] = x[(ia+i)*stride+ZZ] + shz;
4166     }
4167 }
4168
4169 /* Copies PBC shifted super-cell atom coordinates x,y,z to working array */
4170 static void icell_set_x_supersub(int ci,
4171                                  real shx, real shy, real shz,
4172                                  int na_c,
4173                                  int stride, const real *x,
4174                                  nbnxn_list_work_t *work)
4175 {
4176     int   ia, i;
4177     real *x_ci;
4178
4179     x_ci = work->x_ci;
4180
4181     ia = ci*GPU_NSUBCELL*na_c;
4182     for (i = 0; i < GPU_NSUBCELL*na_c; i++)
4183     {
4184         x_ci[i*DIM + XX] = x[(ia+i)*stride + XX] + shx;
4185         x_ci[i*DIM + YY] = x[(ia+i)*stride + YY] + shy;
4186         x_ci[i*DIM + ZZ] = x[(ia+i)*stride + ZZ] + shz;
4187     }
4188 }
4189
4190 #ifdef NBNXN_SEARCH_BB_SIMD4
4191 /* Copies PBC shifted super-cell packed atom coordinates to working array */
4192 static void icell_set_x_supersub_simd4(int ci,
4193                                        real shx, real shy, real shz,
4194                                        int na_c,
4195                                        int stride, const real *x,
4196                                        nbnxn_list_work_t *work)
4197 {
4198     int   si, io, ia, i, j;
4199     real *x_ci;
4200
4201     x_ci = work->x_ci;
4202
4203     for (si = 0; si < GPU_NSUBCELL; si++)
4204     {
4205         for (i = 0; i < na_c; i += STRIDE_PBB)
4206         {
4207             io = si*na_c + i;
4208             ia = ci*GPU_NSUBCELL*na_c + io;
4209             for (j = 0; j < STRIDE_PBB; j++)
4210             {
4211                 x_ci[io*DIM + j + XX*STRIDE_PBB] = x[(ia+j)*stride+XX] + shx;
4212                 x_ci[io*DIM + j + YY*STRIDE_PBB] = x[(ia+j)*stride+YY] + shy;
4213                 x_ci[io*DIM + j + ZZ*STRIDE_PBB] = x[(ia+j)*stride+ZZ] + shz;
4214             }
4215         }
4216     }
4217 }
4218 #endif
4219
4220 static real minimum_subgrid_size_xy(const nbnxn_grid_t *grid)
4221 {
4222     if (grid->bSimple)
4223     {
4224         return min(grid->sx, grid->sy);
4225     }
4226     else
4227     {
4228         return min(grid->sx/GPU_NSUBCELL_X, grid->sy/GPU_NSUBCELL_Y);
4229     }
4230 }
4231
4232 static real effective_buffer_1x1_vs_MxN(const nbnxn_grid_t *gridi,
4233                                         const nbnxn_grid_t *gridj)
4234 {
4235     const real eff_1x1_buffer_fac_overest = 0.1;
4236
4237     /* Determine an atom-pair list cut-off buffer size for atom pairs,
4238      * to be added to rlist (including buffer) used for MxN.
4239      * This is for converting an MxN list to a 1x1 list. This means we can't
4240      * use the normal buffer estimate, as we have an MxN list in which
4241      * some atom pairs beyond rlist are missing. We want to capture
4242      * the beneficial effect of buffering by extra pairs just outside rlist,
4243      * while removing the useless pairs that are further away from rlist.
4244      * (Also the buffer could have been set manually not using the estimate.)
4245      * This buffer size is an overestimate.
4246      * We add 10% of the smallest grid sub-cell dimensions.
4247      * Note that the z-size differs per cell and we don't use this,
4248      * so we overestimate.
4249      * With PME, the 10% value gives a buffer that is somewhat larger
4250      * than the effective buffer with a tolerance of 0.005 kJ/mol/ps.
4251      * Smaller tolerances or using RF lead to a smaller effective buffer,
4252      * so 10% gives a safe overestimate.
4253      */
4254     return eff_1x1_buffer_fac_overest*(minimum_subgrid_size_xy(gridi) +
4255                                        minimum_subgrid_size_xy(gridj));
4256 }
4257
4258 /* Clusters at the cut-off only increase rlist by 60% of their size */
4259 static real nbnxn_rlist_inc_outside_fac = 0.6;
4260
4261 /* Due to the cluster size the effective pair-list is longer than
4262  * that of a simple atom pair-list. This function gives the extra distance.
4263  */
4264 real nbnxn_get_rlist_effective_inc(int cluster_size_j, real atom_density)
4265 {
4266     int  cluster_size_i;
4267     real vol_inc_i, vol_inc_j;
4268
4269     /* We should get this from the setup, but currently it's the same for
4270      * all setups, including GPUs.
4271      */
4272     cluster_size_i = NBNXN_CPU_CLUSTER_I_SIZE;
4273
4274     vol_inc_i = (cluster_size_i - 1)/atom_density;
4275     vol_inc_j = (cluster_size_j - 1)/atom_density;
4276
4277     return nbnxn_rlist_inc_outside_fac*pow(vol_inc_i + vol_inc_j, 1.0/3.0);
4278 }
4279
4280 /* Estimates the interaction volume^2 for non-local interactions */
4281 static real nonlocal_vol2(const gmx_domdec_zones_t *zones, rvec ls, real r)
4282 {
4283     int  z, d;
4284     real cl, ca, za;
4285     real vold_est;
4286     real vol2_est_tot;
4287
4288     vol2_est_tot = 0;
4289
4290     /* Here we simply add up the volumes of 1, 2 or 3 1D decomposition
4291      * not home interaction volume^2. As these volumes are not additive,
4292      * this is an overestimate, but it would only be significant in the limit
4293      * of small cells, where we anyhow need to split the lists into
4294      * as small parts as possible.
4295      */
4296
4297     for (z = 0; z < zones->n; z++)
4298     {
4299         if (zones->shift[z][XX] + zones->shift[z][YY] + zones->shift[z][ZZ] == 1)
4300         {
4301             cl = 0;
4302             ca = 1;
4303             za = 1;
4304             for (d = 0; d < DIM; d++)
4305             {
4306                 if (zones->shift[z][d] == 0)
4307                 {
4308                     cl += 0.5*ls[d];
4309                     ca *= ls[d];
4310                     za *= zones->size[z].x1[d] - zones->size[z].x0[d];
4311                 }
4312             }
4313
4314             /* 4 octants of a sphere */
4315             vold_est  = 0.25*M_PI*r*r*r*r;
4316             /* 4 quarter pie slices on the edges */
4317             vold_est += 4*cl*M_PI/6.0*r*r*r;
4318             /* One rectangular volume on a face */
4319             vold_est += ca*0.5*r*r;
4320
4321             vol2_est_tot += vold_est*za;
4322         }
4323     }
4324
4325     return vol2_est_tot;
4326 }
4327
4328 /* Estimates the average size of a full j-list for super/sub setup */
4329 static int get_nsubpair_max(const nbnxn_search_t nbs,
4330                             int                  iloc,
4331                             real                 rlist,
4332                             int                  min_ci_balanced)
4333 {
4334     const nbnxn_grid_t *grid;
4335     rvec                ls;
4336     real                xy_diag2, r_eff_sup, vol_est, nsp_est, nsp_est_nl;
4337     int                 nsubpair_max;
4338
4339     grid = &nbs->grid[0];
4340
4341     ls[XX] = (grid->c1[XX] - grid->c0[XX])/(grid->ncx*GPU_NSUBCELL_X);
4342     ls[YY] = (grid->c1[YY] - grid->c0[YY])/(grid->ncy*GPU_NSUBCELL_Y);
4343     ls[ZZ] = (grid->c1[ZZ] - grid->c0[ZZ])*grid->ncx*grid->ncy/(grid->nc*GPU_NSUBCELL_Z);
4344
4345     /* The average squared length of the diagonal of a sub cell */
4346     xy_diag2 = ls[XX]*ls[XX] + ls[YY]*ls[YY] + ls[ZZ]*ls[ZZ];
4347
4348     /* The formulas below are a heuristic estimate of the average nsj per si*/
4349     r_eff_sup = rlist + nbnxn_rlist_inc_outside_fac*sqr((grid->na_c - 1.0)/grid->na_c)*sqrt(xy_diag2/3);
4350
4351     if (!nbs->DomDec || nbs->zones->n == 1)
4352     {
4353         nsp_est_nl = 0;
4354     }
4355     else
4356     {
4357         nsp_est_nl =
4358             sqr(grid->atom_density/grid->na_c)*
4359             nonlocal_vol2(nbs->zones, ls, r_eff_sup);
4360     }
4361
4362     if (LOCAL_I(iloc))
4363     {
4364         /* Sub-cell interacts with itself */
4365         vol_est  = ls[XX]*ls[YY]*ls[ZZ];
4366         /* 6/2 rectangular volume on the faces */
4367         vol_est += (ls[XX]*ls[YY] + ls[XX]*ls[ZZ] + ls[YY]*ls[ZZ])*r_eff_sup;
4368         /* 12/2 quarter pie slices on the edges */
4369         vol_est += 2*(ls[XX] + ls[YY] + ls[ZZ])*0.25*M_PI*sqr(r_eff_sup);
4370         /* 4 octants of a sphere */
4371         vol_est += 0.5*4.0/3.0*M_PI*pow(r_eff_sup, 3);
4372
4373         nsp_est = grid->nsubc_tot*vol_est*grid->atom_density/grid->na_c;
4374
4375         /* Subtract the non-local pair count */
4376         nsp_est -= nsp_est_nl;
4377
4378         if (debug)
4379         {
4380             fprintf(debug, "nsp_est local %5.1f non-local %5.1f\n",
4381                     nsp_est, nsp_est_nl);
4382         }
4383     }
4384     else
4385     {
4386         nsp_est = nsp_est_nl;
4387     }
4388
4389     if (min_ci_balanced <= 0 || grid->nc >= min_ci_balanced || grid->nc == 0)
4390     {
4391         /* We don't need to worry */
4392         nsubpair_max = -1;
4393     }
4394     else
4395     {
4396         /* Thus the (average) maximum j-list size should be as follows */
4397         nsubpair_max = max(1, (int)(nsp_est/min_ci_balanced+0.5));
4398
4399         /* Since the target value is a maximum (this avoids high outliers,
4400          * which lead to load imbalance), not average, we add half the
4401          * number of pairs in a cj4 block to get the average about right.
4402          */
4403         nsubpair_max += GPU_NSUBCELL*NBNXN_GPU_JGROUP_SIZE/2;
4404     }
4405
4406     if (debug)
4407     {
4408         fprintf(debug, "nbl nsp estimate %.1f, nsubpair_max %d\n",
4409                 nsp_est, nsubpair_max);
4410     }
4411
4412     return nsubpair_max;
4413 }
4414
4415 /* Debug list print function */
4416 static void print_nblist_ci_cj(FILE *fp, const nbnxn_pairlist_t *nbl)
4417 {
4418     int i, j;
4419
4420     for (i = 0; i < nbl->nci; i++)
4421     {
4422         fprintf(fp, "ci %4d  shift %2d  ncj %3d\n",
4423                 nbl->ci[i].ci, nbl->ci[i].shift,
4424                 nbl->ci[i].cj_ind_end - nbl->ci[i].cj_ind_start);
4425
4426         for (j = nbl->ci[i].cj_ind_start; j < nbl->ci[i].cj_ind_end; j++)
4427         {
4428             fprintf(fp, "  cj %5d  imask %x\n",
4429                     nbl->cj[j].cj,
4430                     nbl->cj[j].excl);
4431         }
4432     }
4433 }
4434
4435 /* Debug list print function */
4436 static void print_nblist_sci_cj(FILE *fp, const nbnxn_pairlist_t *nbl)
4437 {
4438     int i, j4, j, ncp, si;
4439
4440     for (i = 0; i < nbl->nsci; i++)
4441     {
4442         fprintf(fp, "ci %4d  shift %2d  ncj4 %2d\n",
4443                 nbl->sci[i].sci, nbl->sci[i].shift,
4444                 nbl->sci[i].cj4_ind_end - nbl->sci[i].cj4_ind_start);
4445
4446         ncp = 0;
4447         for (j4 = nbl->sci[i].cj4_ind_start; j4 < nbl->sci[i].cj4_ind_end; j4++)
4448         {
4449             for (j = 0; j < NBNXN_GPU_JGROUP_SIZE; j++)
4450             {
4451                 fprintf(fp, "  sj %5d  imask %x\n",
4452                         nbl->cj4[j4].cj[j],
4453                         nbl->cj4[j4].imei[0].imask);
4454                 for (si = 0; si < GPU_NSUBCELL; si++)
4455                 {
4456                     if (nbl->cj4[j4].imei[0].imask & (1U << (j*GPU_NSUBCELL + si)))
4457                     {
4458                         ncp++;
4459                     }
4460                 }
4461             }
4462         }
4463         fprintf(fp, "ci %4d  shift %2d  ncj4 %2d ncp %3d\n",
4464                 nbl->sci[i].sci, nbl->sci[i].shift,
4465                 nbl->sci[i].cj4_ind_end - nbl->sci[i].cj4_ind_start,
4466                 ncp);
4467     }
4468 }
4469
4470 /* Combine pair lists *nbl generated on multiple threads nblc */
4471 static void combine_nblists(int nnbl, nbnxn_pairlist_t **nbl,
4472                             nbnxn_pairlist_t *nblc)
4473 {
4474     int nsci, ncj4, nexcl;
4475     int n, i;
4476
4477     if (nblc->bSimple)
4478     {
4479         gmx_incons("combine_nblists does not support simple lists");
4480     }
4481
4482     nsci  = nblc->nsci;
4483     ncj4  = nblc->ncj4;
4484     nexcl = nblc->nexcl;
4485     for (i = 0; i < nnbl; i++)
4486     {
4487         nsci  += nbl[i]->nsci;
4488         ncj4  += nbl[i]->ncj4;
4489         nexcl += nbl[i]->nexcl;
4490     }
4491
4492     if (nsci > nblc->sci_nalloc)
4493     {
4494         nb_realloc_sci(nblc, nsci);
4495     }
4496     if (ncj4 > nblc->cj4_nalloc)
4497     {
4498         nblc->cj4_nalloc = over_alloc_small(ncj4);
4499         nbnxn_realloc_void((void **)&nblc->cj4,
4500                            nblc->ncj4*sizeof(*nblc->cj4),
4501                            nblc->cj4_nalloc*sizeof(*nblc->cj4),
4502                            nblc->alloc, nblc->free);
4503     }
4504     if (nexcl > nblc->excl_nalloc)
4505     {
4506         nblc->excl_nalloc = over_alloc_small(nexcl);
4507         nbnxn_realloc_void((void **)&nblc->excl,
4508                            nblc->nexcl*sizeof(*nblc->excl),
4509                            nblc->excl_nalloc*sizeof(*nblc->excl),
4510                            nblc->alloc, nblc->free);
4511     }
4512
4513     /* Each thread should copy its own data to the combined arrays,
4514      * as otherwise data will go back and forth between different caches.
4515      */
4516 #pragma omp parallel for num_threads(gmx_omp_nthreads_get(emntPairsearch)) schedule(static)
4517     for (n = 0; n < nnbl; n++)
4518     {
4519         int                     sci_offset;
4520         int                     cj4_offset;
4521         int                     ci_offset;
4522         int                     excl_offset;
4523         int                     i, j4;
4524         const nbnxn_pairlist_t *nbli;
4525
4526         /* Determine the offset in the combined data for our thread */
4527         sci_offset  = nblc->nsci;
4528         cj4_offset  = nblc->ncj4;
4529         ci_offset   = nblc->nci_tot;
4530         excl_offset = nblc->nexcl;
4531
4532         for (i = 0; i < n; i++)
4533         {
4534             sci_offset  += nbl[i]->nsci;
4535             cj4_offset  += nbl[i]->ncj4;
4536             ci_offset   += nbl[i]->nci_tot;
4537             excl_offset += nbl[i]->nexcl;
4538         }
4539
4540         nbli = nbl[n];
4541
4542         for (i = 0; i < nbli->nsci; i++)
4543         {
4544             nblc->sci[sci_offset+i]                = nbli->sci[i];
4545             nblc->sci[sci_offset+i].cj4_ind_start += cj4_offset;
4546             nblc->sci[sci_offset+i].cj4_ind_end   += cj4_offset;
4547         }
4548
4549         for (j4 = 0; j4 < nbli->ncj4; j4++)
4550         {
4551             nblc->cj4[cj4_offset+j4]                   = nbli->cj4[j4];
4552             nblc->cj4[cj4_offset+j4].imei[0].excl_ind += excl_offset;
4553             nblc->cj4[cj4_offset+j4].imei[1].excl_ind += excl_offset;
4554         }
4555
4556         for (j4 = 0; j4 < nbli->nexcl; j4++)
4557         {
4558             nblc->excl[excl_offset+j4] = nbli->excl[j4];
4559         }
4560     }
4561
4562     for (n = 0; n < nnbl; n++)
4563     {
4564         nblc->nsci    += nbl[n]->nsci;
4565         nblc->ncj4    += nbl[n]->ncj4;
4566         nblc->nci_tot += nbl[n]->nci_tot;
4567         nblc->nexcl   += nbl[n]->nexcl;
4568     }
4569 }
4570
4571 static void balance_fep_lists(const nbnxn_search_t  nbs,
4572                               nbnxn_pairlist_set_t *nbl_lists)
4573 {
4574     int       nnbl, th;
4575     int       nri_tot, nrj_tot, nrj_target;
4576     int       th_dest;
4577     t_nblist *nbld;
4578
4579     nnbl = nbl_lists->nnbl;
4580
4581     if (nnbl == 1)
4582     {
4583         /* Nothing to balance */
4584         return;
4585     }
4586
4587     /* Count the total i-lists and pairs */
4588     nri_tot = 0;
4589     nrj_tot = 0;
4590     for (th = 0; th < nnbl; th++)
4591     {
4592         nri_tot += nbl_lists->nbl_fep[th]->nri;
4593         nrj_tot += nbl_lists->nbl_fep[th]->nrj;
4594     }
4595
4596     nrj_target = (nrj_tot + nnbl - 1)/nnbl;
4597
4598     assert(gmx_omp_nthreads_get(emntNonbonded) == nnbl);
4599
4600 #pragma omp parallel for schedule(static) num_threads(nnbl)
4601     for (th = 0; th < nnbl; th++)
4602     {
4603         t_nblist *nbl;
4604
4605         nbl = nbs->work[th].nbl_fep;
4606
4607         /* Note that here we allocate for the total size, instead of
4608          * a per-thread esimate (which is hard to obtain).
4609          */
4610         if (nri_tot > nbl->maxnri)
4611         {
4612             nbl->maxnri = over_alloc_large(nri_tot);
4613             reallocate_nblist(nbl);
4614         }
4615         if (nri_tot > nbl->maxnri || nrj_tot > nbl->maxnrj)
4616         {
4617             nbl->maxnrj = over_alloc_small(nrj_tot);
4618             srenew(nbl->jjnr, nbl->maxnrj);
4619             srenew(nbl->excl_fep, nbl->maxnrj);
4620         }
4621
4622         clear_pairlist_fep(nbl);
4623     }
4624
4625     /* Loop over the source lists and assign and copy i-entries */
4626     th_dest = 0;
4627     nbld    = nbs->work[th_dest].nbl_fep;
4628     for (th = 0; th < nnbl; th++)
4629     {
4630         t_nblist *nbls;
4631         int       i, j;
4632
4633         nbls = nbl_lists->nbl_fep[th];
4634
4635         for (i = 0; i < nbls->nri; i++)
4636         {
4637             int nrj;
4638
4639             /* The number of pairs in this i-entry */
4640             nrj = nbls->jindex[i+1] - nbls->jindex[i];
4641
4642             /* Decide if list th_dest is too large and we should procede
4643              * to the next destination list.
4644              */
4645             if (th_dest+1 < nnbl && nbld->nrj > 0 &&
4646                 nbld->nrj + nrj - nrj_target > nrj_target - nbld->nrj)
4647             {
4648                 th_dest++;
4649                 nbld = nbs->work[th_dest].nbl_fep;
4650             }
4651
4652             nbld->iinr[nbld->nri]  = nbls->iinr[i];
4653             nbld->gid[nbld->nri]   = nbls->gid[i];
4654             nbld->shift[nbld->nri] = nbls->shift[i];
4655
4656             for (j = nbls->jindex[i]; j < nbls->jindex[i+1]; j++)
4657             {
4658                 nbld->jjnr[nbld->nrj]     = nbls->jjnr[j];
4659                 nbld->excl_fep[nbld->nrj] = nbls->excl_fep[j];
4660                 nbld->nrj++;
4661             }
4662             nbld->nri++;
4663             nbld->jindex[nbld->nri] = nbld->nrj;
4664         }
4665     }
4666
4667     /* Swap the list pointers */
4668     for (th = 0; th < nnbl; th++)
4669     {
4670         t_nblist *nbl_tmp;
4671
4672         nbl_tmp                = nbl_lists->nbl_fep[th];
4673         nbl_lists->nbl_fep[th] = nbs->work[th].nbl_fep;
4674         nbs->work[th].nbl_fep  = nbl_tmp;
4675
4676         if (debug)
4677         {
4678             fprintf(debug, "nbl_fep[%d] nri %4d nrj %4d\n",
4679                     th,
4680                     nbl_lists->nbl_fep[th]->nri,
4681                     nbl_lists->nbl_fep[th]->nrj);
4682         }
4683     }
4684 }
4685
4686 /* Returns the next ci to be processes by our thread */
4687 static gmx_bool next_ci(const nbnxn_grid_t *grid,
4688                         int conv,
4689                         int nth, int ci_block,
4690                         int *ci_x, int *ci_y,
4691                         int *ci_b, int *ci)
4692 {
4693     (*ci_b)++;
4694     (*ci)++;
4695
4696     if (*ci_b == ci_block)
4697     {
4698         /* Jump to the next block assigned to this task */
4699         *ci   += (nth - 1)*ci_block;
4700         *ci_b  = 0;
4701     }
4702
4703     if (*ci >= grid->nc*conv)
4704     {
4705         return FALSE;
4706     }
4707
4708     while (*ci >= grid->cxy_ind[*ci_x*grid->ncy + *ci_y + 1]*conv)
4709     {
4710         *ci_y += 1;
4711         if (*ci_y == grid->ncy)
4712         {
4713             *ci_x += 1;
4714             *ci_y  = 0;
4715         }
4716     }
4717
4718     return TRUE;
4719 }
4720
4721 /* Returns the distance^2 for which we put cell pairs in the list
4722  * without checking atom pair distances. This is usually < rlist^2.
4723  */
4724 static float boundingbox_only_distance2(const nbnxn_grid_t *gridi,
4725                                         const nbnxn_grid_t *gridj,
4726                                         real                rlist,
4727                                         gmx_bool            simple)
4728 {
4729     /* If the distance between two sub-cell bounding boxes is less
4730      * than this distance, do not check the distance between
4731      * all particle pairs in the sub-cell, since then it is likely
4732      * that the box pair has atom pairs within the cut-off.
4733      * We use the nblist cut-off minus 0.5 times the average x/y diagonal
4734      * spacing of the sub-cells. Around 40% of the checked pairs are pruned.
4735      * Using more than 0.5 gains at most 0.5%.
4736      * If forces are calculated more than twice, the performance gain
4737      * in the force calculation outweighs the cost of checking.
4738      * Note that with subcell lists, the atom-pair distance check
4739      * is only performed when only 1 out of 8 sub-cells in within range,
4740      * this is because the GPU is much faster than the cpu.
4741      */
4742     real bbx, bby;
4743     real rbb2;
4744
4745     bbx = 0.5*(gridi->sx + gridj->sx);
4746     bby = 0.5*(gridi->sy + gridj->sy);
4747     if (!simple)
4748     {
4749         bbx /= GPU_NSUBCELL_X;
4750         bby /= GPU_NSUBCELL_Y;
4751     }
4752
4753     rbb2 = sqr(max(0, rlist - 0.5*sqrt(bbx*bbx + bby*bby)));
4754
4755 #ifndef GMX_DOUBLE
4756     return rbb2;
4757 #else
4758     return (float)((1+GMX_FLOAT_EPS)*rbb2);
4759 #endif
4760 }
4761
4762 static int get_ci_block_size(const nbnxn_grid_t *gridi,
4763                              gmx_bool bDomDec, int nth)
4764 {
4765     const int ci_block_enum      = 5;
4766     const int ci_block_denom     = 11;
4767     const int ci_block_min_atoms = 16;
4768     int       ci_block;
4769
4770     /* Here we decide how to distribute the blocks over the threads.
4771      * We use prime numbers to try to avoid that the grid size becomes
4772      * a multiple of the number of threads, which would lead to some
4773      * threads getting "inner" pairs and others getting boundary pairs,
4774      * which in turns will lead to load imbalance between threads.
4775      * Set the block size as 5/11/ntask times the average number of cells
4776      * in a y,z slab. This should ensure a quite uniform distribution
4777      * of the grid parts of the different thread along all three grid
4778      * zone boundaries with 3D domain decomposition. At the same time
4779      * the blocks will not become too small.
4780      */
4781     ci_block = (gridi->nc*ci_block_enum)/(ci_block_denom*gridi->ncx*nth);
4782
4783     /* Ensure the blocks are not too small: avoids cache invalidation */
4784     if (ci_block*gridi->na_sc < ci_block_min_atoms)
4785     {
4786         ci_block = (ci_block_min_atoms + gridi->na_sc - 1)/gridi->na_sc;
4787     }
4788
4789     /* Without domain decomposition
4790      * or with less than 3 blocks per task, divide in nth blocks.
4791      */
4792     if (!bDomDec || ci_block*3*nth > gridi->nc)
4793     {
4794         ci_block = (gridi->nc + nth - 1)/nth;
4795     }
4796
4797     return ci_block;
4798 }
4799
4800 /* Generates the part of pair-list nbl assigned to our thread */
4801 static void nbnxn_make_pairlist_part(const nbnxn_search_t nbs,
4802                                      const nbnxn_grid_t *gridi,
4803                                      const nbnxn_grid_t *gridj,
4804                                      nbnxn_search_work_t *work,
4805                                      const nbnxn_atomdata_t *nbat,
4806                                      const t_blocka *excl,
4807                                      real rlist,
4808                                      int nb_kernel_type,
4809                                      int ci_block,
4810                                      gmx_bool bFBufferFlag,
4811                                      int nsubpair_max,
4812                                      gmx_bool progBal,
4813                                      int min_ci_balanced,
4814                                      int th, int nth,
4815                                      nbnxn_pairlist_t *nbl,
4816                                      t_nblist *nbl_fep)
4817 {
4818     int               na_cj_2log;
4819     matrix            box;
4820     real              rl2, rl_fep2 = 0;
4821     float             rbb2;
4822     int               d;
4823     int               ci_b, ci, ci_x, ci_y, ci_xy, cj;
4824     ivec              shp;
4825     int               tx, ty, tz;
4826     int               shift;
4827     gmx_bool          bMakeList;
4828     real              shx, shy, shz;
4829     int               conv_i, cell0_i;
4830     const nbnxn_bb_t *bb_i = NULL;
4831 #ifdef NBNXN_BBXXXX
4832     const float      *pbb_i = NULL;
4833 #endif
4834     const float      *bbcz_i, *bbcz_j;
4835     const int        *flags_i;
4836     real              bx0, bx1, by0, by1, bz0, bz1;
4837     real              bz1_frac;
4838     real              d2cx, d2z, d2z_cx, d2z_cy, d2zx, d2zxy, d2xy;
4839     int               cxf, cxl, cyf, cyf_x, cyl;
4840     int               cx, cy;
4841     int               c0, c1, cs, cf, cl;
4842     int               ndistc;
4843     int               ncpcheck;
4844     int               gridi_flag_shift = 0, gridj_flag_shift = 0;
4845     unsigned int     *gridj_flag       = NULL;
4846     int               ncj_old_i, ncj_old_j;
4847
4848     nbs_cycle_start(&work->cc[enbsCCsearch]);
4849
4850     if (gridj->bSimple != nbl->bSimple)
4851     {
4852         gmx_incons("Grid incompatible with pair-list");
4853     }
4854
4855     sync_work(nbl);
4856     nbl->na_sc = gridj->na_sc;
4857     nbl->na_ci = gridj->na_c;
4858     nbl->na_cj = nbnxn_kernel_to_cj_size(nb_kernel_type);
4859     na_cj_2log = get_2log(nbl->na_cj);
4860
4861     nbl->rlist  = rlist;
4862
4863     if (bFBufferFlag)
4864     {
4865         /* Determine conversion of clusters to flag blocks */
4866         gridi_flag_shift = 0;
4867         while ((nbl->na_ci<<gridi_flag_shift) < NBNXN_BUFFERFLAG_SIZE)
4868         {
4869             gridi_flag_shift++;
4870         }
4871         gridj_flag_shift = 0;
4872         while ((nbl->na_cj<<gridj_flag_shift) < NBNXN_BUFFERFLAG_SIZE)
4873         {
4874             gridj_flag_shift++;
4875         }
4876
4877         gridj_flag = work->buffer_flags.flag;
4878     }
4879
4880     copy_mat(nbs->box, box);
4881
4882     rl2 = nbl->rlist*nbl->rlist;
4883
4884     if (nbs->bFEP && !nbl->bSimple)
4885     {
4886         /* Determine an atom-pair list cut-off distance for FEP atom pairs.
4887          * We should not simply use rlist, since then we would not have
4888          * the small, effective buffering of the NxN lists.
4889          * The buffer is on overestimate, but the resulting cost for pairs
4890          * beyond rlist is neglible compared to the FEP pairs within rlist.
4891          */
4892         rl_fep2 = nbl->rlist + effective_buffer_1x1_vs_MxN(gridi, gridj);
4893
4894         if (debug)
4895         {
4896             fprintf(debug, "nbl_fep atom-pair rlist %f\n", rl_fep2);
4897         }
4898         rl_fep2 = rl_fep2*rl_fep2;
4899     }
4900
4901     rbb2 = boundingbox_only_distance2(gridi, gridj, nbl->rlist, nbl->bSimple);
4902
4903     if (debug)
4904     {
4905         fprintf(debug, "nbl bounding box only distance %f\n", sqrt(rbb2));
4906     }
4907
4908     /* Set the shift range */
4909     for (d = 0; d < DIM; d++)
4910     {
4911         /* Check if we need periodicity shifts.
4912          * Without PBC or with domain decomposition we don't need them.
4913          */
4914         if (d >= ePBC2npbcdim(nbs->ePBC) || nbs->dd_dim[d])
4915         {
4916             shp[d] = 0;
4917         }
4918         else
4919         {
4920             if (d == XX &&
4921                 box[XX][XX] - fabs(box[YY][XX]) - fabs(box[ZZ][XX]) < sqrt(rl2))
4922             {
4923                 shp[d] = 2;
4924             }
4925             else
4926             {
4927                 shp[d] = 1;
4928             }
4929         }
4930     }
4931
4932     if (nbl->bSimple && !gridi->bSimple)
4933     {
4934         conv_i  = gridi->na_sc/gridj->na_sc;
4935         bb_i    = gridi->bb_simple;
4936         bbcz_i  = gridi->bbcz_simple;
4937         flags_i = gridi->flags_simple;
4938     }
4939     else
4940     {
4941         conv_i  = 1;
4942 #ifdef NBNXN_BBXXXX
4943         if (gridi->bSimple)
4944         {
4945             bb_i  = gridi->bb;
4946         }
4947         else
4948         {
4949             pbb_i = gridi->pbb;
4950         }
4951 #else
4952         /* We use the normal bounding box format for both grid types */
4953         bb_i  = gridi->bb;
4954 #endif
4955         bbcz_i  = gridi->bbcz;
4956         flags_i = gridi->flags;
4957     }
4958     cell0_i = gridi->cell0*conv_i;
4959
4960     bbcz_j = gridj->bbcz;
4961
4962     if (conv_i != 1)
4963     {
4964         /* Blocks of the conversion factor - 1 give a large repeat count
4965          * combined with a small block size. This should result in good
4966          * load balancing for both small and large domains.
4967          */
4968         ci_block = conv_i - 1;
4969     }
4970     if (debug)
4971     {
4972         fprintf(debug, "nbl nc_i %d col.av. %.1f ci_block %d\n",
4973                 gridi->nc, gridi->nc/(double)(gridi->ncx*gridi->ncy), ci_block);
4974     }
4975
4976     ndistc   = 0;
4977     ncpcheck = 0;
4978
4979     /* Initially ci_b and ci to 1 before where we want them to start,
4980      * as they will both be incremented in next_ci.
4981      */
4982     ci_b = -1;
4983     ci   = th*ci_block - 1;
4984     ci_x = 0;
4985     ci_y = 0;
4986     while (next_ci(gridi, conv_i, nth, ci_block, &ci_x, &ci_y, &ci_b, &ci))
4987     {
4988         if (nbl->bSimple && flags_i[ci] == 0)
4989         {
4990             continue;
4991         }
4992
4993         ncj_old_i = nbl->ncj;
4994
4995         d2cx = 0;
4996         if (gridj != gridi && shp[XX] == 0)
4997         {
4998             if (nbl->bSimple)
4999             {
5000                 bx1 = bb_i[ci].upper[BB_X];
5001             }
5002             else
5003             {
5004                 bx1 = gridi->c0[XX] + (ci_x+1)*gridi->sx;
5005             }
5006             if (bx1 < gridj->c0[XX])
5007             {
5008                 d2cx = sqr(gridj->c0[XX] - bx1);
5009
5010                 if (d2cx >= rl2)
5011                 {
5012                     continue;
5013                 }
5014             }
5015         }
5016
5017         ci_xy = ci_x*gridi->ncy + ci_y;
5018
5019         /* Loop over shift vectors in three dimensions */
5020         for (tz = -shp[ZZ]; tz <= shp[ZZ]; tz++)
5021         {
5022             shz = tz*box[ZZ][ZZ];
5023
5024             bz0 = bbcz_i[ci*NNBSBB_D  ] + shz;
5025             bz1 = bbcz_i[ci*NNBSBB_D+1] + shz;
5026
5027             if (tz == 0)
5028             {
5029                 d2z = 0;
5030             }
5031             else if (tz < 0)
5032             {
5033                 d2z = sqr(bz1);
5034             }
5035             else
5036             {
5037                 d2z = sqr(bz0 - box[ZZ][ZZ]);
5038             }
5039
5040             d2z_cx = d2z + d2cx;
5041
5042             if (d2z_cx >= rl2)
5043             {
5044                 continue;
5045             }
5046
5047             bz1_frac =
5048                 bz1/((real)(gridi->cxy_ind[ci_xy+1] - gridi->cxy_ind[ci_xy]));
5049             if (bz1_frac < 0)
5050             {
5051                 bz1_frac = 0;
5052             }
5053             /* The check with bz1_frac close to or larger than 1 comes later */
5054
5055             for (ty = -shp[YY]; ty <= shp[YY]; ty++)
5056             {
5057                 shy = ty*box[YY][YY] + tz*box[ZZ][YY];
5058
5059                 if (nbl->bSimple)
5060                 {
5061                     by0 = bb_i[ci].lower[BB_Y] + shy;
5062                     by1 = bb_i[ci].upper[BB_Y] + shy;
5063                 }
5064                 else
5065                 {
5066                     by0 = gridi->c0[YY] + (ci_y  )*gridi->sy + shy;
5067                     by1 = gridi->c0[YY] + (ci_y+1)*gridi->sy + shy;
5068                 }
5069
5070                 get_cell_range(by0, by1,
5071                                gridj->ncy, gridj->c0[YY], gridj->sy, gridj->inv_sy,
5072                                d2z_cx, rl2,
5073                                &cyf, &cyl);
5074
5075                 if (cyf > cyl)
5076                 {
5077                     continue;
5078                 }
5079
5080                 d2z_cy = d2z;
5081                 if (by1 < gridj->c0[YY])
5082                 {
5083                     d2z_cy += sqr(gridj->c0[YY] - by1);
5084                 }
5085                 else if (by0 > gridj->c1[YY])
5086                 {
5087                     d2z_cy += sqr(by0 - gridj->c1[YY]);
5088                 }
5089
5090                 for (tx = -shp[XX]; tx <= shp[XX]; tx++)
5091                 {
5092                     shift = XYZ2IS(tx, ty, tz);
5093
5094 #ifdef NBNXN_SHIFT_BACKWARD
5095                     if (gridi == gridj && shift > CENTRAL)
5096                     {
5097                         continue;
5098                     }
5099 #endif
5100
5101                     shx = tx*box[XX][XX] + ty*box[YY][XX] + tz*box[ZZ][XX];
5102
5103                     if (nbl->bSimple)
5104                     {
5105                         bx0 = bb_i[ci].lower[BB_X] + shx;
5106                         bx1 = bb_i[ci].upper[BB_X] + shx;
5107                     }
5108                     else
5109                     {
5110                         bx0 = gridi->c0[XX] + (ci_x  )*gridi->sx + shx;
5111                         bx1 = gridi->c0[XX] + (ci_x+1)*gridi->sx + shx;
5112                     }
5113
5114                     get_cell_range(bx0, bx1,
5115                                    gridj->ncx, gridj->c0[XX], gridj->sx, gridj->inv_sx,
5116                                    d2z_cy, rl2,
5117                                    &cxf, &cxl);
5118
5119                     if (cxf > cxl)
5120                     {
5121                         continue;
5122                     }
5123
5124                     if (nbl->bSimple)
5125                     {
5126                         new_ci_entry(nbl, cell0_i+ci, shift, flags_i[ci]);
5127                     }
5128                     else
5129                     {
5130                         new_sci_entry(nbl, cell0_i+ci, shift);
5131                     }
5132
5133 #ifndef NBNXN_SHIFT_BACKWARD
5134                     if (cxf < ci_x)
5135 #else
5136                     if (shift == CENTRAL && gridi == gridj &&
5137                         cxf < ci_x)
5138 #endif
5139                     {
5140                         /* Leave the pairs with i > j.
5141                          * x is the major index, so skip half of it.
5142                          */
5143                         cxf = ci_x;
5144                     }
5145
5146                     if (nbl->bSimple)
5147                     {
5148                         set_icell_bb_simple(bb_i, ci, shx, shy, shz,
5149                                             nbl->work->bb_ci);
5150                     }
5151                     else
5152                     {
5153 #ifdef NBNXN_BBXXXX
5154                         set_icell_bbxxxx_supersub(pbb_i, ci, shx, shy, shz,
5155                                                   nbl->work->pbb_ci);
5156 #else
5157                         set_icell_bb_supersub(bb_i, ci, shx, shy, shz,
5158                                               nbl->work->bb_ci);
5159 #endif
5160                     }
5161
5162                     nbs->icell_set_x(cell0_i+ci, shx, shy, shz,
5163                                      gridi->na_c, nbat->xstride, nbat->x,
5164                                      nbl->work);
5165
5166                     for (cx = cxf; cx <= cxl; cx++)
5167                     {
5168                         d2zx = d2z;
5169                         if (gridj->c0[XX] + cx*gridj->sx > bx1)
5170                         {
5171                             d2zx += sqr(gridj->c0[XX] + cx*gridj->sx - bx1);
5172                         }
5173                         else if (gridj->c0[XX] + (cx+1)*gridj->sx < bx0)
5174                         {
5175                             d2zx += sqr(gridj->c0[XX] + (cx+1)*gridj->sx - bx0);
5176                         }
5177
5178 #ifndef NBNXN_SHIFT_BACKWARD
5179                         if (gridi == gridj &&
5180                             cx == 0 && cyf < ci_y)
5181 #else
5182                         if (gridi == gridj &&
5183                             cx == 0 && shift == CENTRAL && cyf < ci_y)
5184 #endif
5185                         {
5186                             /* Leave the pairs with i > j.
5187                              * Skip half of y when i and j have the same x.
5188                              */
5189                             cyf_x = ci_y;
5190                         }
5191                         else
5192                         {
5193                             cyf_x = cyf;
5194                         }
5195
5196                         for (cy = cyf_x; cy <= cyl; cy++)
5197                         {
5198                             c0 = gridj->cxy_ind[cx*gridj->ncy+cy];
5199                             c1 = gridj->cxy_ind[cx*gridj->ncy+cy+1];
5200 #ifdef NBNXN_SHIFT_BACKWARD
5201                             if (gridi == gridj &&
5202                                 shift == CENTRAL && c0 < ci)
5203                             {
5204                                 c0 = ci;
5205                             }
5206 #endif
5207
5208                             d2zxy = d2zx;
5209                             if (gridj->c0[YY] + cy*gridj->sy > by1)
5210                             {
5211                                 d2zxy += sqr(gridj->c0[YY] + cy*gridj->sy - by1);
5212                             }
5213                             else if (gridj->c0[YY] + (cy+1)*gridj->sy < by0)
5214                             {
5215                                 d2zxy += sqr(gridj->c0[YY] + (cy+1)*gridj->sy - by0);
5216                             }
5217                             if (c1 > c0 && d2zxy < rl2)
5218                             {
5219                                 cs = c0 + (int)(bz1_frac*(c1 - c0));
5220                                 if (cs >= c1)
5221                                 {
5222                                     cs = c1 - 1;
5223                                 }
5224
5225                                 d2xy = d2zxy - d2z;
5226
5227                                 /* Find the lowest cell that can possibly
5228                                  * be within range.
5229                                  */
5230                                 cf = cs;
5231                                 while (cf > c0 &&
5232                                        (bbcz_j[cf*NNBSBB_D+1] >= bz0 ||
5233                                         d2xy + sqr(bbcz_j[cf*NNBSBB_D+1] - bz0) < rl2))
5234                                 {
5235                                     cf--;
5236                                 }
5237
5238                                 /* Find the highest cell that can possibly
5239                                  * be within range.
5240                                  */
5241                                 cl = cs;
5242                                 while (cl < c1-1 &&
5243                                        (bbcz_j[cl*NNBSBB_D] <= bz1 ||
5244                                         d2xy + sqr(bbcz_j[cl*NNBSBB_D] - bz1) < rl2))
5245                                 {
5246                                     cl++;
5247                                 }
5248
5249 #ifdef NBNXN_REFCODE
5250                                 {
5251                                     /* Simple reference code, for debugging,
5252                                      * overrides the more complex code above.
5253                                      */
5254                                     int k;
5255                                     cf = c1;
5256                                     cl = -1;
5257                                     for (k = c0; k < c1; k++)
5258                                     {
5259                                         if (box_dist2(bx0, bx1, by0, by1, bz0, bz1, bb+k) < rl2 &&
5260                                             k < cf)
5261                                         {
5262                                             cf = k;
5263                                         }
5264                                         if (box_dist2(bx0, bx1, by0, by1, bz0, bz1, bb+k) < rl2 &&
5265                                             k > cl)
5266                                         {
5267                                             cl = k;
5268                                         }
5269                                     }
5270                                 }
5271 #endif
5272
5273                                 if (gridi == gridj)
5274                                 {
5275                                     /* We want each atom/cell pair only once,
5276                                      * only use cj >= ci.
5277                                      */
5278 #ifndef NBNXN_SHIFT_BACKWARD
5279                                     cf = max(cf, ci);
5280 #else
5281                                     if (shift == CENTRAL)
5282                                     {
5283                                         cf = max(cf, ci);
5284                                     }
5285 #endif
5286                                 }
5287
5288                                 if (cf <= cl)
5289                                 {
5290                                     /* For f buffer flags with simple lists */
5291                                     ncj_old_j = nbl->ncj;
5292
5293                                     switch (nb_kernel_type)
5294                                     {
5295                                         case nbnxnk4x4_PlainC:
5296                                             check_subcell_list_space_simple(nbl, cl-cf+1);
5297
5298                                             make_cluster_list_simple(gridj,
5299                                                                      nbl, ci, cf, cl,
5300                                                                      (gridi == gridj && shift == CENTRAL),
5301                                                                      nbat->x,
5302                                                                      rl2, rbb2,
5303                                                                      &ndistc);
5304                                             break;
5305 #ifdef GMX_NBNXN_SIMD_4XN
5306                                         case nbnxnk4xN_SIMD_4xN:
5307                                             check_subcell_list_space_simple(nbl, ci_to_cj(na_cj_2log, cl-cf)+2);
5308                                             make_cluster_list_simd_4xn(gridj,
5309                                                                        nbl, ci, cf, cl,
5310                                                                        (gridi == gridj && shift == CENTRAL),
5311                                                                        nbat->x,
5312                                                                        rl2, rbb2,
5313                                                                        &ndistc);
5314                                             break;
5315 #endif
5316 #ifdef GMX_NBNXN_SIMD_2XNN
5317                                         case nbnxnk4xN_SIMD_2xNN:
5318                                             check_subcell_list_space_simple(nbl, ci_to_cj(na_cj_2log, cl-cf)+2);
5319                                             make_cluster_list_simd_2xnn(gridj,
5320                                                                         nbl, ci, cf, cl,
5321                                                                         (gridi == gridj && shift == CENTRAL),
5322                                                                         nbat->x,
5323                                                                         rl2, rbb2,
5324                                                                         &ndistc);
5325                                             break;
5326 #endif
5327                                         case nbnxnk8x8x8_PlainC:
5328                                         case nbnxnk8x8x8_CUDA:
5329                                             check_subcell_list_space_supersub(nbl, cl-cf+1);
5330                                             for (cj = cf; cj <= cl; cj++)
5331                                             {
5332                                                 make_cluster_list_supersub(gridi, gridj,
5333                                                                            nbl, ci, cj,
5334                                                                            (gridi == gridj && shift == CENTRAL && ci == cj),
5335                                                                            nbat->xstride, nbat->x,
5336                                                                            rl2, rbb2,
5337                                                                            &ndistc);
5338                                             }
5339                                             break;
5340                                     }
5341                                     ncpcheck += cl - cf + 1;
5342
5343                                     if (bFBufferFlag && nbl->ncj > ncj_old_j)
5344                                     {
5345                                         int cbf, cbl, cb;
5346
5347                                         cbf = nbl->cj[ncj_old_j].cj >> gridj_flag_shift;
5348                                         cbl = nbl->cj[nbl->ncj-1].cj >> gridj_flag_shift;
5349                                         for (cb = cbf; cb <= cbl; cb++)
5350                                         {
5351                                             gridj_flag[cb] = 1U<<th;
5352                                         }
5353                                     }
5354                                 }
5355                             }
5356                         }
5357                     }
5358
5359                     /* Set the exclusions for this ci list */
5360                     if (nbl->bSimple)
5361                     {
5362                         set_ci_top_excls(nbs,
5363                                          nbl,
5364                                          shift == CENTRAL && gridi == gridj,
5365                                          gridj->na_c_2log,
5366                                          na_cj_2log,
5367                                          &(nbl->ci[nbl->nci]),
5368                                          excl);
5369
5370                         if (nbs->bFEP)
5371                         {
5372                             make_fep_list(nbs, nbat, nbl,
5373                                           shift == CENTRAL && gridi == gridj,
5374                                           &(nbl->ci[nbl->nci]),
5375                                           gridi, gridj, nbl_fep);
5376                         }
5377                     }
5378                     else
5379                     {
5380                         set_sci_top_excls(nbs,
5381                                           nbl,
5382                                           shift == CENTRAL && gridi == gridj,
5383                                           gridj->na_c_2log,
5384                                           &(nbl->sci[nbl->nsci]),
5385                                           excl);
5386
5387                         if (nbs->bFEP)
5388                         {
5389                             make_fep_list_supersub(nbs, nbat, nbl,
5390                                                    shift == CENTRAL && gridi == gridj,
5391                                                    &(nbl->sci[nbl->nsci]),
5392                                                    shx, shy, shz,
5393                                                    rl_fep2,
5394                                                    gridi, gridj, nbl_fep);
5395                         }
5396                     }
5397
5398                     /* Close this ci list */
5399                     if (nbl->bSimple)
5400                     {
5401                         close_ci_entry_simple(nbl);
5402                     }
5403                     else
5404                     {
5405                         close_ci_entry_supersub(nbl,
5406                                                 nsubpair_max,
5407                                                 progBal, min_ci_balanced,
5408                                                 th, nth);
5409                     }
5410                 }
5411             }
5412         }
5413
5414         if (bFBufferFlag && nbl->ncj > ncj_old_i)
5415         {
5416             work->buffer_flags.flag[(gridi->cell0+ci)>>gridi_flag_shift] = 1U<<th;
5417         }
5418     }
5419
5420     work->ndistc = ndistc;
5421
5422     nbs_cycle_stop(&work->cc[enbsCCsearch]);
5423
5424     if (debug)
5425     {
5426         fprintf(debug, "number of distance checks %d\n", ndistc);
5427         fprintf(debug, "ncpcheck %s %d\n", gridi == gridj ? "local" : "non-local",
5428                 ncpcheck);
5429
5430         if (nbl->bSimple)
5431         {
5432             print_nblist_statistics_simple(debug, nbl, nbs, rlist);
5433         }
5434         else
5435         {
5436             print_nblist_statistics_supersub(debug, nbl, nbs, rlist);
5437         }
5438
5439         if (nbs->bFEP)
5440         {
5441             fprintf(debug, "nbl FEP list pairs: %d\n", nbl_fep->nrj);
5442         }
5443     }
5444 }
5445
5446 static void reduce_buffer_flags(const nbnxn_search_t        nbs,
5447                                 int                         nsrc,
5448                                 const nbnxn_buffer_flags_t *dest)
5449 {
5450     int                 s, b;
5451     const unsigned int *flag;
5452
5453     for (s = 0; s < nsrc; s++)
5454     {
5455         flag = nbs->work[s].buffer_flags.flag;
5456
5457         for (b = 0; b < dest->nflag; b++)
5458         {
5459             dest->flag[b] |= flag[b];
5460         }
5461     }
5462 }
5463
5464 static void print_reduction_cost(const nbnxn_buffer_flags_t *flags, int nout)
5465 {
5466     int nelem, nkeep, ncopy, nred, b, c, out;
5467
5468     nelem = 0;
5469     nkeep = 0;
5470     ncopy = 0;
5471     nred  = 0;
5472     for (b = 0; b < flags->nflag; b++)
5473     {
5474         if (flags->flag[b] == 1)
5475         {
5476             /* Only flag 0 is set, no copy of reduction required */
5477             nelem++;
5478             nkeep++;
5479         }
5480         else if (flags->flag[b] > 0)
5481         {
5482             c = 0;
5483             for (out = 0; out < nout; out++)
5484             {
5485                 if (flags->flag[b] & (1U<<out))
5486                 {
5487                     c++;
5488                 }
5489             }
5490             nelem += c;
5491             if (c == 1)
5492             {
5493                 ncopy++;
5494             }
5495             else
5496             {
5497                 nred += c;
5498             }
5499         }
5500     }
5501
5502     fprintf(debug, "nbnxn reduction: #flag %d #list %d elem %4.2f, keep %4.2f copy %4.2f red %4.2f\n",
5503             flags->nflag, nout,
5504             nelem/(double)(flags->nflag),
5505             nkeep/(double)(flags->nflag),
5506             ncopy/(double)(flags->nflag),
5507             nred/(double)(flags->nflag));
5508 }
5509
5510 /* Perform a count (linear) sort to sort the smaller lists to the end.
5511  * This avoids load imbalance on the GPU, as large lists will be
5512  * scheduled and executed first and the smaller lists later.
5513  * Load balancing between multi-processors only happens at the end
5514  * and there smaller lists lead to more effective load balancing.
5515  * The sorting is done on the cj4 count, not on the actual pair counts.
5516  * Not only does this make the sort faster, but it also results in
5517  * better load balancing than using a list sorted on exact load.
5518  * This function swaps the pointer in the pair list to avoid a copy operation.
5519  */
5520 static void sort_sci(nbnxn_pairlist_t *nbl)
5521 {
5522     nbnxn_list_work_t *work;
5523     int                m, i, s, s0, s1;
5524     nbnxn_sci_t       *sci_sort;
5525
5526     if (nbl->ncj4 <= nbl->nsci)
5527     {
5528         /* nsci = 0 or all sci have size 1, sorting won't change the order */
5529         return;
5530     }
5531
5532     work = nbl->work;
5533
5534     /* We will distinguish differences up to double the average */
5535     m = (2*nbl->ncj4)/nbl->nsci;
5536
5537     if (m + 1 > work->sort_nalloc)
5538     {
5539         work->sort_nalloc = over_alloc_large(m + 1);
5540         srenew(work->sort, work->sort_nalloc);
5541     }
5542
5543     if (work->sci_sort_nalloc != nbl->sci_nalloc)
5544     {
5545         work->sci_sort_nalloc = nbl->sci_nalloc;
5546         nbnxn_realloc_void((void **)&work->sci_sort,
5547                            0,
5548                            work->sci_sort_nalloc*sizeof(*work->sci_sort),
5549                            nbl->alloc, nbl->free);
5550     }
5551
5552     /* Count the entries of each size */
5553     for (i = 0; i <= m; i++)
5554     {
5555         work->sort[i] = 0;
5556     }
5557     for (s = 0; s < nbl->nsci; s++)
5558     {
5559         i = min(m, nbl->sci[s].cj4_ind_end - nbl->sci[s].cj4_ind_start);
5560         work->sort[i]++;
5561     }
5562     /* Calculate the offset for each count */
5563     s0            = work->sort[m];
5564     work->sort[m] = 0;
5565     for (i = m - 1; i >= 0; i--)
5566     {
5567         s1            = work->sort[i];
5568         work->sort[i] = work->sort[i + 1] + s0;
5569         s0            = s1;
5570     }
5571
5572     /* Sort entries directly into place */
5573     sci_sort = work->sci_sort;
5574     for (s = 0; s < nbl->nsci; s++)
5575     {
5576         i = min(m, nbl->sci[s].cj4_ind_end - nbl->sci[s].cj4_ind_start);
5577         sci_sort[work->sort[i]++] = nbl->sci[s];
5578     }
5579
5580     /* Swap the sci pointers so we use the new, sorted list */
5581     work->sci_sort = nbl->sci;
5582     nbl->sci       = sci_sort;
5583 }
5584
5585 /* Make a local or non-local pair-list, depending on iloc */
5586 void nbnxn_make_pairlist(const nbnxn_search_t  nbs,
5587                          nbnxn_atomdata_t     *nbat,
5588                          const t_blocka       *excl,
5589                          real                  rlist,
5590                          int                   min_ci_balanced,
5591                          nbnxn_pairlist_set_t *nbl_list,
5592                          int                   iloc,
5593                          int                   nb_kernel_type,
5594                          t_nrnb               *nrnb)
5595 {
5596     nbnxn_grid_t      *gridi, *gridj;
5597     gmx_bool           bGPUCPU;
5598     int                nzi, zi, zj0, zj1, zj;
5599     int                nsubpair_max;
5600     int                th;
5601     int                nnbl;
5602     nbnxn_pairlist_t **nbl;
5603     int                ci_block;
5604     gmx_bool           CombineNBLists;
5605     gmx_bool           progBal;
5606     int                np_tot, np_noq, np_hlj, nap;
5607
5608     /* Check if we are running hybrid GPU + CPU nbnxn mode */
5609     bGPUCPU = (!nbs->grid[0].bSimple && nbl_list->bSimple);
5610
5611     nnbl            = nbl_list->nnbl;
5612     nbl             = nbl_list->nbl;
5613     CombineNBLists  = nbl_list->bCombined;
5614
5615     if (debug)
5616     {
5617         fprintf(debug, "ns making %d nblists\n", nnbl);
5618     }
5619
5620     nbat->bUseBufferFlags = (nbat->nout > 1);
5621     /* We should re-init the flags before making the first list */
5622     if (nbat->bUseBufferFlags && (LOCAL_I(iloc) || bGPUCPU))
5623     {
5624         init_buffer_flags(&nbat->buffer_flags, nbat->natoms);
5625     }
5626
5627     if (nbl_list->bSimple)
5628     {
5629         switch (nb_kernel_type)
5630         {
5631 #ifdef GMX_NBNXN_SIMD_4XN
5632             case nbnxnk4xN_SIMD_4xN:
5633                 nbs->icell_set_x = icell_set_x_simd_4xn;
5634                 break;
5635 #endif
5636 #ifdef GMX_NBNXN_SIMD_2XNN
5637             case nbnxnk4xN_SIMD_2xNN:
5638                 nbs->icell_set_x = icell_set_x_simd_2xnn;
5639                 break;
5640 #endif
5641             default:
5642                 nbs->icell_set_x = icell_set_x_simple;
5643                 break;
5644         }
5645     }
5646     else
5647     {
5648 #ifdef NBNXN_SEARCH_BB_SIMD4
5649         nbs->icell_set_x = icell_set_x_supersub_simd4;
5650 #else
5651         nbs->icell_set_x = icell_set_x_supersub;
5652 #endif
5653     }
5654
5655     if (LOCAL_I(iloc))
5656     {
5657         /* Only zone (grid) 0 vs 0 */
5658         nzi = 1;
5659         zj0 = 0;
5660         zj1 = 1;
5661     }
5662     else
5663     {
5664         nzi = nbs->zones->nizone;
5665     }
5666
5667     if (!nbl_list->bSimple && min_ci_balanced > 0)
5668     {
5669         nsubpair_max = get_nsubpair_max(nbs, iloc, rlist, min_ci_balanced);
5670     }
5671     else
5672     {
5673         nsubpair_max = 0;
5674     }
5675
5676     /* Clear all pair-lists */
5677     for (th = 0; th < nnbl; th++)
5678     {
5679         clear_pairlist(nbl[th]);
5680
5681         if (nbs->bFEP)
5682         {
5683             clear_pairlist_fep(nbl_list->nbl_fep[th]);
5684         }
5685     }
5686
5687     for (zi = 0; zi < nzi; zi++)
5688     {
5689         gridi = &nbs->grid[zi];
5690
5691         if (NONLOCAL_I(iloc))
5692         {
5693             zj0 = nbs->zones->izone[zi].j0;
5694             zj1 = nbs->zones->izone[zi].j1;
5695             if (zi == 0)
5696             {
5697                 zj0++;
5698             }
5699         }
5700         for (zj = zj0; zj < zj1; zj++)
5701         {
5702             gridj = &nbs->grid[zj];
5703
5704             if (debug)
5705             {
5706                 fprintf(debug, "ns search grid %d vs %d\n", zi, zj);
5707             }
5708
5709             nbs_cycle_start(&nbs->cc[enbsCCsearch]);
5710
5711             if (nbl[0]->bSimple && !gridi->bSimple)
5712             {
5713                 /* Hybrid list, determine blocking later */
5714                 ci_block = 0;
5715             }
5716             else
5717             {
5718                 ci_block = get_ci_block_size(gridi, nbs->DomDec, nnbl);
5719             }
5720
5721             /* With GPU: generate progressively smaller lists for
5722              * load balancing for local only or non-local with 2 zones.
5723              */
5724             progBal = (LOCAL_I(iloc) || nbs->zones->n <= 2);
5725
5726 #pragma omp parallel for num_threads(nnbl) schedule(static)
5727             for (th = 0; th < nnbl; th++)
5728             {
5729                 /* Re-init the thread-local work flag data before making
5730                  * the first list (not an elegant conditional).
5731                  */
5732                 if (nbat->bUseBufferFlags && ((zi == 0 && zj == 0) ||
5733                                               (bGPUCPU && zi == 0 && zj == 1)))
5734                 {
5735                     init_buffer_flags(&nbs->work[th].buffer_flags, nbat->natoms);
5736                 }
5737
5738                 if (CombineNBLists && th > 0)
5739                 {
5740                     clear_pairlist(nbl[th]);
5741                 }
5742
5743                 /* Divide the i super cell equally over the nblists */
5744                 nbnxn_make_pairlist_part(nbs, gridi, gridj,
5745                                          &nbs->work[th], nbat, excl,
5746                                          rlist,
5747                                          nb_kernel_type,
5748                                          ci_block,
5749                                          nbat->bUseBufferFlags,
5750                                          nsubpair_max,
5751                                          progBal, min_ci_balanced,
5752                                          th, nnbl,
5753                                          nbl[th],
5754                                          nbl_list->nbl_fep[th]);
5755             }
5756             nbs_cycle_stop(&nbs->cc[enbsCCsearch]);
5757
5758             np_tot = 0;
5759             np_noq = 0;
5760             np_hlj = 0;
5761             for (th = 0; th < nnbl; th++)
5762             {
5763                 inc_nrnb(nrnb, eNR_NBNXN_DIST2, nbs->work[th].ndistc);
5764
5765                 if (nbl_list->bSimple)
5766                 {
5767                     np_tot += nbl[th]->ncj;
5768                     np_noq += nbl[th]->work->ncj_noq;
5769                     np_hlj += nbl[th]->work->ncj_hlj;
5770                 }
5771                 else
5772                 {
5773                     /* This count ignores potential subsequent pair pruning */
5774                     np_tot += nbl[th]->nci_tot;
5775                 }
5776             }
5777             nap                   = nbl[0]->na_ci*nbl[0]->na_cj;
5778             nbl_list->natpair_ljq = (np_tot - np_noq)*nap - np_hlj*nap/2;
5779             nbl_list->natpair_lj  = np_noq*nap;
5780             nbl_list->natpair_q   = np_hlj*nap/2;
5781
5782             if (CombineNBLists && nnbl > 1)
5783             {
5784                 nbs_cycle_start(&nbs->cc[enbsCCcombine]);
5785
5786                 combine_nblists(nnbl-1, nbl+1, nbl[0]);
5787
5788                 nbs_cycle_stop(&nbs->cc[enbsCCcombine]);
5789             }
5790         }
5791     }
5792
5793     if (!nbl_list->bSimple)
5794     {
5795         /* Sort the entries on size, large ones first */
5796         if (CombineNBLists || nnbl == 1)
5797         {
5798             sort_sci(nbl[0]);
5799         }
5800         else
5801         {
5802 #pragma omp parallel for num_threads(nnbl) schedule(static)
5803             for (th = 0; th < nnbl; th++)
5804             {
5805                 sort_sci(nbl[th]);
5806             }
5807         }
5808     }
5809
5810     if (nbat->bUseBufferFlags)
5811     {
5812         reduce_buffer_flags(nbs, nnbl, &nbat->buffer_flags);
5813     }
5814
5815     if (nbs->bFEP)
5816     {
5817         /* Balance the free-energy lists over all the threads */
5818         balance_fep_lists(nbs, nbl_list);
5819     }
5820
5821     /* Special performance logging stuff (env.var. GMX_NBNXN_CYCLE) */
5822     if (LOCAL_I(iloc))
5823     {
5824         nbs->search_count++;
5825     }
5826     if (nbs->print_cycles &&
5827         (!nbs->DomDec || (nbs->DomDec && !LOCAL_I(iloc))) &&
5828         nbs->search_count % 100 == 0)
5829     {
5830         nbs_cycle_print(stderr, nbs);
5831     }
5832
5833     if (debug && (CombineNBLists && nnbl > 1))
5834     {
5835         if (nbl[0]->bSimple)
5836         {
5837             print_nblist_statistics_simple(debug, nbl[0], nbs, rlist);
5838         }
5839         else
5840         {
5841             print_nblist_statistics_supersub(debug, nbl[0], nbs, rlist);
5842         }
5843     }
5844
5845     if (debug)
5846     {
5847         if (gmx_debug_at)
5848         {
5849             if (nbl[0]->bSimple)
5850             {
5851                 print_nblist_ci_cj(debug, nbl[0]);
5852             }
5853             else
5854             {
5855                 print_nblist_sci_cj(debug, nbl[0]);
5856             }
5857         }
5858
5859         if (nbat->bUseBufferFlags)
5860         {
5861             print_reduction_cost(&nbat->buffer_flags, nnbl);
5862         }
5863     }
5864 }