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