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