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