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