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