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